       Re: := vs. =

• To: mathgroup at smc.vnet.net
• Subject: [mg8943] Re: [mg8858] := vs. =
• From: penny at suu.edu (Des Penny)
• Date: Sat, 4 Oct 1997 22:08:19 -0400
• Sender: owner-wri-mathgroup at wolfram.com

```>When I define a function on Mathematica, I use f[x_]=xxxxx, without
>using a colon.  It seems to work just fine.  Is there a risk in leaving
>out the colon?  Thanks.
>
>Frank

Hi Frank:

Yes there is a danger.  If you don't understand the difference, I recommend
that you use the delayed definition :=

Look at the following code to understand the difference:

In:
c=5;
f[x_]= Sin[c x]
g[x_] := Sin[c x]

We can now get information on how these functions are stored:

In:
?f

Out:
Global`f
f[x_] = Sin[5*x]

In:
?g

Out:
Global`g
f[x_] = Sin[c*x]

If we now change the value of c, we see that the definition of f is
unchanged whereas g is changed:

In:
c=6;
f[x]

Out:
Sin[5 x]

In:
g[x]

Out:
Sin[6 x]

Thus, the delayed definition, :=, causes Mma to store the definition
without using the current value of c.  For most uses this is the preferred
way to define a function.

There are however a few cases where it is preferable to use the immediate
definition:

In:
Clear[f];
f[x_]=Integrate[Sin[t], {t,0,x}]
Timing[Table[f[x], {x,0,5,0.01}]][]

Out:
0.183 Second

In:
Clear[g];
g[x_]:=Integrate[Sin[t], {t,0,x}]
Timing[Table[g[x], {x,0,5,0.01}]][]

Out:
47.53 Second

The reason for the above becomes clear when you look at how Mma stores the
definitions of f and g:

?f
Global`f
f[x_]=1-Cos[x]

?g
Global`g
g[x_]:=Integrate[Sin[t],{t,0,x}]

Therefore, the immediate definition, =, forces an immediate evaluation of
the integral.  The answer is stored as the definition of f.  The delayed
definition, :=, just stores the integral.  Thus g must be integrated afresh
for each of the 500 values of x between 0 and 5.

I use the immediate definition whenever I need to force the evaluated form
of the definition to be stored by Mma.  Otherwise I use the delayed
definition.

Hope this helps.

Cheers,

Des Penny

-------------------------------
Des Penny
Physical Science Dept.
Southern Utah University
Cedar City, UT 84720

VOICE: (Office): (801) 586-7708
(Home)  : (801) 586-2286
FAX:    (801) 865-8051
e-mail: penny at suu.edu
-------------------------------

```

• Prev by Date: Fwd: FindRoot
• Next by Date: Re:
• Previous by thread: RE: := vs. =