MuPAD Pro Computing Essentials, 2nd Edition

Heron formula

We can use Heron formula to practice how to create procedures and develop simple algorithms. Here are presented a few stages of developing the Heron procedure.

heron1 := proc(a,b,c)
begin
 s := (a + b + c)/2;
 sqrt(s*(s - a)*(s - b)*(s - c))
end:
 
heron1(3,4,5)

6


 

heron2 := proc(a,b,c)
begin
   if a<0 or b<0 or c<0 then
      print("This is not a real triangle")
   else
      s := (a + b + c)/2;
      sqrt(s*(s - a)*(s - b)*(s - c))
   end
end:
 
heron2(3,5,9)


    
heron3 := proc(a,b,c)
begin
   if a<0 or b<0 or c<0 or (a-b-c)*(b-a-c)*(c-a-b)>0
   then
      print("This is not a real triangle.")
   else
      s := (a + b + c)/2;
      sqrt(s*(s - a)*(s - b)*(s - c))
   end
end:
heron3(-1,1,1)

"This is not a real triangle."

heron := proc(a,b,c)
   local s;
begin
   if a<0 or b<0 or c<0 or (a-b-c)*(b-a-c)*(c-a-b)>0
   then
      print("This is not a real triangle")
   else
      s := (a + b + c)/2;
      return(sqrt(s*(s - a)*(s - b)*(s - c)));
   end
end:
 
heron(-1,1,2)
 

"This is not a real triangle."

 

© Miroslaw Majewski, Abu Dhabi,  Update  26-10-2004