       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=2.

>Out=2.
>----------------- When I use = instead of := it works OK.
>Why ?

The difference between "=" and ":=" is when evaluation occurs

=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:=
f[x_]=Integrate[y Sinh[y],{y,0,x}]

Out=
x cosh(x)-sinh(x)

In:=
Timing[Plot[f[x],{x,0,5}];]

Out=
{0.013135 Second,Null}

versus

In:=
g[x_]:=Integrate[y Sinh[y],{y,0,x}]

In:=
Timing[Plot[g[x],{x,0,5}];]

Out=
{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:=
x=4;
t[x_]=2 x

Out=
8

In:=
t

Out=
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/ArcCsch is 3?
• Previous by thread: Re: Fuction definition
• Next by thread: Re: Fuction definition