MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: mathematica newbie trouble

  • To: mathgroup at
  • Subject: [mg99317] Re: mathematica newbie trouble
  • From: Bill Rowe <readnews at>
  • Date: Sat, 2 May 2009 06:02:07 -0400 (EDT)

On 5/1/09 at 5:52 AM, yangshuai at (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?

You would have gotten what you expected with SetDelayed had you
defined s as:

s[a_, b_, c_]:=(a + b + c)/2

When you write s:=(a+b+c)/2 you are telling Mathematica s is a
function of *global* variables. When you write k[a_,b_,c_]:= you
are telling Mathematica k a function of *local* variables. So,
given no global assignment made to a,b and c, s gets evaluated
to (a+b+c)/2 and is not evaluated further. But the other
instances of a,b, and c in the definition of k are assigned the
values supplied as arguments to k.

Use your version with SetDelayed and do the following:

In[16]:= a = b = c = 2;
k[m, n, p]

Out[17]= Sqrt[3] Sqrt[(3-m) (3-n) (3-p)]

Since, I set a,b and c to 2, s evaluates to 3. So, 3 appears
everywhere s is in the definition of k. Note:

In[18]:= k[3, 4, 5]

Out[18]= 0

Here s defined with global values of a,b and c gets evaluated to
3. And k uses the local value of a to be 3 per the definition.
So the term s-a gets evaluated to 0 causing the entire product
to be 0. Given the way s is used in k, I would have written the
code as

s = (a + b + c)/2;
k[a_, b_, c_] := Sqrt[s (s - a) (s - b) (s - c)]

or possibly

k[a_, b_, c_] := Block[{s}, Sqrt[s (s - a) (s - b) (s - c)]/.s
-> (a + b + c)/2]

Note, I have not used a semicolon to terminate the definition of
k using SetDelayed since there is no output to be suppressed.
That is the right hand side is not evaluated by definition when
k is defined using SetDelayed. Consequently, there is no output
to be suppressed.

  • Prev by Date: Re: mathematica newbie trouble
  • Next by Date: Re: Nested numerical integration
  • Previous by thread: Re: mathematica newbie trouble
  • Next by thread: Re: issues with GraphPlot