The area of a triangle

PROBLEM
Given the lengths of three sides of a triangle X, Y, Z. How to calculate the area of this triangle?

Numerically unstable and numerically stable solution
The classical formula due to Heron of Alexandria first calculates a semiperimeter, S, as half the sum of the sides, and then evaluates the area as in the following internal function HERON

IMPLEMENTATION
Unit: internal function
 
Interface: the functions SQRT
 
Parameters: positive real numbers X, Y, Z - lengths of three sides of a triangle
a positive integer P - number of significant digits of result, default is 9
 
Returns: the area of a triangle

 


HERON: procedure
parse arg X, Y, Z, P
if P = "" then P = 9; numeric digits P
S = (X + Y + Z) / 2
return SQRT(S * (S - X) * (S - Y) * (S - Z), P)

 

This function is numerically unstable for needle-shape triangle. W. Kahan describes a good, numerically stable, function. It follows:


ATRIAN: procedure
parse arg X, Y, Z, P
if P = "" then P = 9; numeric digits P
/* sorting X, Y, Z so that X>=Y>=Z */
if Y > X
  then do; W = X; X = Y; Y = W; end
if Z > X
  then do; W = X; X = Z; Z = W; end
if Z > Y
  then do; W = Y; Y = Z; Z = W; end
if Z < (X - Y)
  then call ERROR "No such triangle exist"
  else do
    W1 =  X + Y + Z
    W2 = -X + Y + Z
    W3 =  X - Y + Z
    W4 =  X + Y - Z
    return SQRT(W1 * W2 * W3 * W4, P) / 4
  end
 
ERROR: say ARG(1); exit

 

Example (W. Kahan)
The following program


X = 100.01; Y = 99.995; Z = 0.025
say " 5 sig. dig. Heron" HERON(X, Y, Z, 5)
say "20 sig. dig. Heron" HERON(X, Y, Z, 20)
say " 5 sig. dig. Kahan" ATRIAN(X, Y, Z, 5)
say "20 sig. dig. Kahan" ATRIAN(X, Y, Z, 20)
exit
...

displays on the screen:


 5 sig. dig. Heron 1.5813
20 sig. dig. Heron 1.0000249921876952771
 5 sig. dig. Kahan 1.0000
20 sig. dig. Kahan 1.0000249921876952771

Literature
Kahan W., Mathematics Written in Sand
CO-AUTHOR
Robert D. Acker, Jr. - improving of the ATRIAN procedure


Cover Contents Index Main page Rexx page   Mail

last modified 18th March 2005
Copyright © 2000-2005 Vladimir Zabrodsky
Czech Republic