Heron's formula and degenerate triangles in JavaScript
Advanced · 4 min read
Sometimes you know the three sides of a triangle but not its height: a plot of land measured along its fences, a mesh in a 3D model, a shape on a map. Heron's formula gives the area from the three sides alone. It is exact on paper. In a computer, for one kind of triangle, it quietly loses half its digits.
In this tutorial you will write Heron's formula, check it on two famous triangles, then try a long, thin "needle" triangle and see it go wrong. You will fix it with a rearrangement by William Kahan that does the same math in a safer order. You will also see what both give for a flat triangle and for three sides that can't make a triangle at all. You need to know Math.sqrt, sort and arrow functions.
Heron's formula
Call the sides a, b and c. First find the half-perimeter, half of the distance around:
s = (a + b + c) / 2
area = sqrt(s * (s - a) * (s - b) * (s - c))
For a 3-4-5 triangle, s is 6, and the area is the square root of 6 * 3 * 2 * 1 = 36, which is 6.
Losing digits by subtracting
A JavaScript number keeps about 16 significant digits. Subtract two numbers that agree in most of those digits, and only the last few, the least reliable ones, are left. For example, 100000.00004 - 100000 should be 0.00004, but only the digits after the shared part survive the subtraction. This is called cancellation. Keep it in mind: it is the whole story of the needle triangle.
Here is the exercise. Try it on your own first if you like, then read on and we will build it together.
97 Heron's formula, and the triangle that breaks it
hardCompute a triangle's area from its three sides with Heron's formula. Check it on 3-4-5 and 13-14-15, then try the sides 100000, 99999.99979 and 0.00029 — a needle — and compare Heron with Kahan's rearrangement of the same formula. Say what each returns for a degenerate and an impossible triangle.
Stuck? Three hints, smallest first
- 1. Heron: with
sthe half-perimeter, the area issqrt(s (s-a) (s-b) (s-c)). - 2. For a needle,
s - ais a tiny difference of two nearly equal numbers. That is where the digits go. - 3. Kahan sorts the sides descending and groups them as
(a+(b+c))(c-(a-b))(c+(a-b))(a+(b-c)), divided by 4.
Step 1: Heron's formula in code
const heron = (a, b, c) => {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
};
console.log(heron(3, 4, 5), heron(13, 14, 15)); // 6 84
console.log(heron(2, 2, 2), Math.sqrt(3)); // 1.7320508075688772 1.7320508075688772
The 3-4-5 triangle has area 6, the 13-14-15 has area 84, and an equilateral triangle with side 2 has area √3, exactly as on paper.
Step 2: the needle
Now a triangle with one side of 100000, a second of 99999.99979 and a tiny third side of 0.00029. It is real, just very long and thin.
const needle = [100000, 99999.99979, 0.00029];
const s = (needle[0] + needle[1] + needle[2]) / 2;
console.log(s - needle[0]); // 0.000039999998989515007
console.log(heron(...needle)); // 9.999999809638329
s - a should be 0.00004, and it comes out as 0.000039999998989515007. That is only right to about eight digits. s and a agree in their first ten digits, so the subtraction throws those away and keeps the rounding noise. The error then goes through the multiplication and the square root. The true area of this triangle is 10.000000077021038, so Heron is out by about 2.7e-7.
heron(...needle) uses spread syntax: the three items of the array become the three arguments.
Step 3: Kahan's rearrangement
Kahan's version multiplies the same four factors, but grouped so that no factor is built from one big, nearly-cancelling subtraction.
const kahan = (a, b, c) => {
const [x, y, z] = [a, b, c].slice().sort((p, q) => q - p);
return Math.sqrt((x + (y + z)) * (z - (x - y)) * (z + (x - y)) * (x + (y - z))) / 4;
};
console.log(kahan(...needle)); // 10.000000077021038
First it sorts the sides from longest to shortest, so x is the longest. The brackets matter: (z - (x - y)) works out x - y first, a small exact difference, before using it. Written with the brackets anywhere else, the cancellation comes back. The result here is the correct area, to the last digit.
.slice() copies the array first, so the sort doesn't change the caller's array.
Step 4: on normal triangles, they agree
console.log(kahan(3, 4, 5), kahan(13, 14, 15), kahan(2, 2, 2) === heron(2, 2, 2)); // 6 84 true
On well-shaped triangles both give the same answer, so you lose nothing by always using Kahan's.
Step 5: a flat triangle
A degenerate triangle is one where two sides exactly meet the third, so the "triangle" is a straight line.
console.log(heron(1, 2, 3), kahan(1, 2, 3)); // 0 0
1 + 2 is exactly 3, so one factor is exactly 0, and the area is 0.
Step 6: an impossible triangle
Sides of 1, 2 and 10 can't meet: the two short sides together don't reach across the long one.
console.log(heron(1, 2, 10), kahan(1, 2, 10)); // NaN NaN
The product under the square root goes negative, and Math.sqrt of a negative number is NaN. It doesn't throw an error, so it can spread silently through later sums.
Step 7: check the triangle first
The triangle inequality says each pair of sides must add up to more than the third.
const isTriangle = (a, b, c) =>
a > 0 && b > 0 && c > 0 && a + b > c && a + c > b && b + c > a;
console.log(isTriangle(3, 4, 5), isTriangle(1, 2, 3), isTriangle(1, 2, 10), isTriangle(...needle)); // true false false true
Check this before computing an area, so bad input is caught where it enters. Notice the needle passes: it is a real triangle, just a hard one for arithmetic.
The full solution
The answer panel has heron, kahan and isTriangle, with the true needle area worked out separately in exact arithmetic, and prints both formulas on every triangle above. Press Run to see the output.
const heron = (a, b, c) => {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
};
// Kahan's rearrangement. Same algebra, different grouping, and the sort matters.
const kahan = (a, b, c) => {
const [x, y, z] = [a, b, c].slice().sort((p, q) => q - p);
return Math.sqrt((x + (y + z)) * (z - (x - y)) * (z + (x - y)) * (x + (y - z))) / 4;
};
const isTriangle = (a, b, c) =>
a > 0 && b > 0 && c > 0 && a + b > c && a + c > b && b + c > a;
const needle = [100000, 99999.99979, 0.00029];
// Computed offline in exact rational arithmetic, for the triangle whose sides
// are the doubles nearest those three decimals: 10.0000000770210383232996...
const exactNeedleArea = 10.000000077021038;
console.log('3-4-5 :', heron(3, 4, 5), kahan(3, 4, 5));
console.log('13-14-15 :', heron(13, 14, 15), kahan(13, 14, 15));
console.log('equilateral:', heron(2, 2, 2), 'against sqrt(3)', Math.sqrt(3));
console.log('needle, Heron:', heron(needle[0], needle[1], needle[2]));
console.log('needle, Kahan:', kahan(needle[0], needle[1], needle[2]));
console.log('the exact area:', exactNeedleArea);
console.log('Heron is out by:', Math.abs(heron(needle[0], needle[1], needle[2]) - exactNeedleArea));
console.log('degenerate 1-2-3:', heron(1, 2, 3), kahan(1, 2, 3));
console.log('impossible 1-2-10:', heron(1, 2, 10), kahan(1, 2, 10));
console.log('valid? :', isTriangle(3, 4, 5), isTriangle(1, 2, 3), isTriangle(1, 2, 10));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the 3-4-5 triangle has area 6 and the 13-14-15 has area 84', [heron(3, 4, 5), heron(13, 14, 15)], [6, 84]);
test('an equilateral triangle of side 2 has area sqrt(3), to the last bit', [heron(2, 2, 2), heron(2, 2, 2) === Math.sqrt(3)], [1.7320508075688772, true]);
test('Kahan agrees on every well-shaped triangle, so it costs nothing to use', [kahan(3, 4, 5), kahan(13, 14, 15), kahan(2, 2, 2) === heron(2, 2, 2)], [6, 84, true]);
test('on the needle the two disagree from the eighth significant digit', [heron(needle[0], needle[1], needle[2]), kahan(needle[0], needle[1], needle[2])], [9.999999809638329, 10.000000077021038]);
test('and Kahan is the one telling the truth, exactly', kahan(needle[0], needle[1], needle[2]) === exactNeedleArea, true);
test('Heron is out by 2.67e-7, which is a relative error of 2.7e-8', [Math.abs(heron(needle[0], needle[1], needle[2]) - exactNeedleArea) > 1e-7, Math.abs(kahan(needle[0], needle[1], needle[2]) - exactNeedleArea) === 0], [true, true]);
test('a degenerate triangle, where two sides just meet the third, has area 0', [heron(1, 2, 3), kahan(1, 2, 3)], [0, 0]);
test('an impossible triangle gives NaN from both, since the product goes negative', [Number.isNaN(heron(1, 2, 10)), Number.isNaN(kahan(1, 2, 10))], [true, true]);
test('so validity is a separate check, and the needle does pass it', [isTriangle(3, 4, 5), isTriangle(1, 2, 3), isTriangle(1, 2, 10), isTriangle(needle[0], needle[1], needle[2])], [true, false, false, true]);
Heron's formula is exact algebra and unstable arithmetic. For a needle triangle — one very long side and two others that nearly equal it — the half-perimeter s is almost exactly a, so s - a is a difference of two numbers that agree in their first eleven digits. Most of the significant digits cancel away, and the survivors are then multiplied and square-rooted. Heron returns 9.999999809638329 where the true area is 10.000000077021038: about eight good digits lost out of sixteen.
Kahan's version computes the same product, grouped so that each factor is formed from small differences of similar magnitude rather than from one catastrophic subtraction. It returns the correctly rounded answer, bit for bit. The descending sort is not decoration — the grouping (z - (x - y)) only behaves if x is the longest side. And on well-shaped triangles both formulas agree exactly, so there is no reason to keep the fragile one.
The edges are worth knowing too. A degenerate triangle gives exactly 0 from both, because one factor is exactly 0. An impossible one gives NaN, since a negative product goes into Math.sqrt. That NaN is not a substitute for validation: it arrives silently, propagates through every later sum, and by the time it surfaces you have lost the input that caused it. Check the triangle inequality first, and note that the needle passes — it is a real triangle, just a hard one.
Common mistakes
- Using plain Heron for thin triangles.
s - acancels and you lose about half the digits. Use Kahan's version. - Skipping the sort in Kahan's version. The grouping only works when
xis the longest side. - Relying on
NaNto catch bad sides. Check the triangle inequality first, so the error is caught where it starts.
Try it yourself
- Compute the area of a triangle with sides 5, 5 and 8 with both formulas.
- Change
kahanto returnnullwhen the sides failisTriangle. - Make a needle of your own: sides 1, 1 and 1e-7. Compare
heronandkahan, and work out the true area with base times height over 2.