Re: mathematica newbie trouble

• To: mathgroup at smc.vnet.net
• Subject: [mg99282] Re: mathematica newbie trouble
• From: David Bailey <dave at removedbailey.co.uk>
• Date: Sat, 2 May 2009 05:55:35 -0400 (EDT)
• References: <gtegon\$1vu\$1@smc.vnet.net>

```Guapo wrote:
> i wrote the following mathematica code:
>
> s := (a + b + c)/2;
> k[a_, b_, c_] := Sqrt[s (s - a) (s - b) (s - c)];
> k[3, 4, 5]
> k[5, 9, 12]
>
> when run it, i can't get the write answer. but i change setDelayed(:=)
> to set(=), everything works ok
>
> s = (a + b + c)/2;
> k[a_, b_, c_] = Sqrt[s (s - a) (s - b) (s - c)];
> k[3, 4, 5]
> k[5, 9, 12]
>
> i did a google search for the difference of set and setDelayed,
> however, i still can't understand it for the upper described problem,
> could anyone explain it? great thanks.
>
Probably the easiest way to see the difference here, is to try it both
ways, and execute ?k after each, to see how it is defined. With Set, the
contents of the Sqrt get evaluated as the function is being set up,
and this injects the definition of s into the function. With SetDelayed,
s is only evaluated when needed, and the 'a' in the expression for s is
different from the pattern argument a.

Obviously you do not want to get into this mess.

A good elementary rule of thumb is to use Set when defining variables,
and SetDelayed when defining functions - which is what you half did
originally. I would then define k thus:

s=(a+b+c)/2;
k[aa_, bb_, cc_] :=
Sqrt[s (s - a) (s - b) (s - c)] /. {a -> aa, b -> bb, c -> cc};

Now the Sqrt will get completely evaluated, using the definition for s
each time you use k, and this will be followed by a set of explicit
substitutions.

David Bailey
http://www.dbaileyconsultancy.co.uk

```

• Prev by Date: Re: mathematica newbie trouble
• Next by Date: MemoryInUse and Print
• Previous by thread: Re: mathematica newbie trouble
• Next by thread: Re: mathematica newbie trouble