[Date Index]
[Thread Index]
[Author Index]
Re: Fuction definition
*To*: mathgroup at smc.vnet.net
*Subject*: [mg73694] Re: Fuction definition
*From*: Bill Rowe <readnewsciv at sbcglobal.net>
*Date*: Sat, 24 Feb 2007 02:30:42 -0500 (EST)
On 2/23/07 at 4:42 AM, bar at ANTYSPAM.ap.krakow.pl wrote:
>When I try : ------------------ p = 1; f1[x_] := p Sin[Pi x]; p = 2;
>f2[x_] := p Sin[Pi x];
>f1[0.5]
>f2[0.5]
>Out[26]=2.
>Out[27]=2.
>----------------- When I use = instead of := it works OK.
>Why ?
The difference between "=" and ":=" is when evaluation occurs
and the assignment is made.
=46or "=" evaluation & assignment occurs immediately after you hit
shift return
=46or ":=" assignment occurs later when the function is being used.
>It is safely to use "=" in function definition ?
Yes, it is safe and in some cases better than ":=". For example, consider
In[40]:=
f[x_]=Integrate[y Sinh[y],{y,0,x}]
Out[40]=
x cosh(x)-sinh(x)
In[41]:=
Timing[Plot[f[x],{x,0,5}];]
Out[41]=
{0.013135 Second,Null}
versus
In[42]:=
g[x_]:=Integrate[y Sinh[y],{y,0,x}]
In[43]:=
Timing[Plot[g[x],{x,0,5}];]
Out[43]=
{0.975745 Second,Null}
In with ":=", the integral is being computed for each sample but
was only computed once when "=" is used. Hence, Mathematica must
do a lot more work with the second version.
But this should not be taken as meaning "=" is better than ":="
since it can cause other problems.
=46or example consider
In[48]:=
x=4;
t[x_]=2 x
Out[49]=
8
In[50]:=
t[3]
Out[50]=
8
Here x was assigned the value 4 and when the assignment to t was
made 2 x was evaluated to 8 and assigned to t. And since _
matches any expression, t will always return 8 which is
generally not what is desired.
--
To reply via email subtract one hundred and four
Prev by Date:
**Re: split again**
Next by Date:
**Re: Showing that ArcSinh[2]/ArcCsch[2] is 3?**
Previous by thread:
**Re: Fuction definition**
Next by thread:
**Re: Fuction definition**
| |