 
 
 
 
 
 
Re: mathematica newbie trouble
- To: mathgroup at smc.vnet.net
- Subject: [mg99281] Re: [mg99276] mathematica newbie trouble
- From: Murray Eisenberg <murray at math.umass.edu>
- Date: Sat, 2 May 2009 05:55:24 -0400 (EDT)
- Organization: Mathematics & Statistics, Univ. of Mass./Amherst
- References: <200905010952.FAA02056@smc.vnet.net>
- Reply-to: murray at math.umass.edu
Briefly, SetDelayed (:=) does not evaluate what's on the right-hand-side 
until the left hand side is evaluated.  The trouble with your code is 
that you really want s to be a function of a,b,c, that is, to get its 
value after a, b, c get their values.  And then you need to make the s 
on the right-hand side of your definition of k to depend explicitly on 
a,b,c.  So change the two definitions to the following (and no 
terminating semicolons are required):
   s[a_, b_, c_] := (a + b + c)/2
   k[a_, b_, c_] :=
       Sqrt[s[a, b, c](s[a, b, c] - a)(s[a, b, c] - b)(s[a, b, c] - c)]
Then your k should work as expected.
A bit better, avoid the long expression now inside the square-root by 
making some use of Mathematica's list-processing ability and functional 
programming:
   k[a_, b_, c_] := Sqrt[Times @@ (s[a, b, c] - {0, a, b, c})]
What happens on the right-hand side there is the following:   The 
quantity s[a,b,c] is evaluated just once. From it each of the numbers 0, 
a, b, c is subtracted ("in parallel").  Then Times is Apply'ed to the 
result, in other words, the differences are multiplied.
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.
> 
-- 
Murray Eisenberg                     murray at math.umass.edu
Mathematics & Statistics Dept.
Lederle Graduate Research Tower      phone 413 549-1020 (H)
University of Massachusetts                413 545-2859 (W)
710 North Pleasant Street            fax   413 545-1801
Amherst, MA 01003-9305
- References:
- mathematica newbie trouble
- From: Guapo <yangshuai@gmail.com>
 
 
- mathematica newbie trouble

