MATLAB simulation showing Heron's formula instability

449 Views Asked by At

I am trying to compute in MATLAB the error introduced using Heron's formula for computing the area of a triangle with $a \approx b + c$. I am confronting the value of the area with the one obtained with Kahan formula for the area of triangles.

Below there is my code, the use of array is due to the fact that I will create a plot showing how the error varies. The problem is that I get no error or it is very, very small, much smaller than single precision (I am using single precision in order to deal with few decimal digits).

A = [50+40+0.0001 40 50];

a = single(A(1));
b = single(A(2));
c = single(A(3));
A1 = 1/4 * sqrt((a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c));

A = sort(A);
a = single(A(3));
b = single(A(2));
c = single(A(1));
disp(A);
A2 = 1/4 * sqrt((a+(b+c))*(c-(a-b))*(c+(a-b))*(a+(b-c)));

errRel = abs((double(A1) - double(A2))/double(A1));
errAbs = abs(double(A1) - double(A2));

disp(sprintf('errRel = %.15f',errRel));
disp(sprintf('errAbs = %.15f',errAbs));

This is my result, as you can see the error is too small, while it is written everywhere that Heron formula is a bad idea to compute areas.

enter image description here