Emmanuel Akinfulubi

JavaScriptMath

Triangle area: base-height vs Heron's formula in JavaScript

Intermediate · 5 min read

The area of a triangle is the space inside its three sides. You need it for land surveys, roof and sail sizes, and in computer graphics, where every 3D model is built from thousands of tiny triangles. The formula from school, half the base times the height, needs the height. Often you only know the three side lengths. Heron's formula works from those alone.

In this tutorial you will compute a triangle's area both ways and check they agree. Then you will try Heron on sides that can't form a triangle, and on a very long, thin triangle where the formula as usually written gives a visibly wrong answer. You will fix it by rearranging the same formula. You need to know arrow functions and Math.sqrt.

Half base times height

Picture a triangle sitting on its base. The height is the straight-up distance from the base to the top corner. The area is half of base times height, because the triangle is exactly half of the rectangle around it.

A 3-4-5 triangle has a right angle, so the side of 4 can be the base and the side of 3 the height: ½ × 4 × 3 = 6.

Heron's formula

For sides a, b and c, first find the semi-perimeter s, half the distance around:

Output

s = (a + b + c) / 2
area = √( s × (s − a) × (s − b) × (s − c) )

For 3, 4 and 5: s = 6, so the area is √(6 × 3 × 2 × 1) = √36 = 6. The same answer, without needing to know the height.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

74 A triangle, by base and height and by Heron

fair

Find the area of a 3-4-5 triangle both ways: half base times height, and Heron's formula from the three sides. Then try Heron on sides that cannot form a triangle, and on a very thin one where it loses most of its accuracy.

Stuck? Three hints, smallest first
  1. 1. Heron: s = (a + b + c) / 2, then Math.sqrt(s * (s - a) * (s - b) * (s - c)).
  2. 2. If one side is longer than the other two together, the product under the root goes negative.
  3. 3. For a thin triangle, s - a subtracts two nearly equal numbers, and most of the digits cancel.

Step 1: both formulas

Step 1

const byBaseHeight = (base, height) => 0.5 * base * height;
const heron = (a, b, c) => {
  const s = (a + b + c) / 2;
  return Math.sqrt(s * (s - a) * (s - b) * (s - c));
};
console.log(byBaseHeight(4, 3), heron(3, 4, 5)); // 6 6

They agree. The Heron version is a block-body arrow function, with { } and return, because it needs a line to work out s first.

Step 2: some other triangles

Step 2

console.log(heron(7, 8, 9));                    // 26.832815729997478
console.log(heron(2, 2, 2) === Math.sqrt(3));   // true

A 7-8-9 triangle has no neat height, but Heron handles it. An equilateral triangle with sides of 2 has an area of exactly √3, and the result matches Math.sqrt(3) to the last digit.

Step 3: sides that can't make a triangle

Each side of a triangle must be shorter than the other two put together. Otherwise the two short sides can't meet. Try 1, 2 and 3, and then 1, 2 and 10:

Step 3

console.log(heron(1, 2, 3));  // 0
console.log(heron(1, 2, 10)); // NaN

1 + 2 is exactly 3, so the "triangle" lies flat: three points on one line. The area is 0, which is honest.

For 1, 2 and 10, the short sides can't reach. s is 6.5, and s - c is 6.5 - 10 = -3.5. The product under the square root goes negative, and the square root of a negative number is NaN (Not a Number). There is no error, so always check for NaN if your sides come from user input.

Step 4: a needle triangle

Now a very thin triangle: two sides of a billion, and a third side of 0.00001. The height is a billion and the short side is the base, so the true area is ½ × 0.00001 × 1,000,000,000 = 5000.

Step 4

const needle = [1e9, 1e9, 1e-5];
const trueArea = 0.5 * 1e-5 * 1e9;          // base times height, to the last digit
console.log(trueArea);        // 5000
console.log(heron(...needle)); // 5006.7901611328125

...needle spreads the array into three arguments. Heron says 5006.79. That is not a tiny wobble in the last digit: it is wrong in the fourth digit.

Step 5: why it goes wrong

s is half the total: (1e9 + 1e9 + 0.00001) / 2, just a hair above a billion. Then s - a takes a billion away from almost exactly a billion.

JavaScript numbers carry about 16 significant digits. A billion uses 10 of them before the decimal point, leaving only about 6 for the part after. When you subtract two numbers that are nearly equal, the matching leading digits cancel, and what is left is mostly rounding noise. This is called cancellation. That noise is then multiplied by the other, much larger factors.

Step 5

const relativeError = (heron(...needle) - trueArea) / trueArea;
console.log(Math.round(relativeError * 1e6) / 1e6); // 0.001358

The answer is about 0.14% too big.

Step 6: the same formula, rearranged

The fix is a rearrangement known as Kahan's version. Sort the sides from longest to shortest, as x, y and z, then group the sums so no step subtracts two nearly equal large numbers:

Step 6

function stableHeron(a, b, c) {
  const [x, y, z] = [a, b, c].sort((p, q) => q - p);
  return Math.sqrt((x + (y + z)) * (z - (x - y)) * (z + (x - y)) * (x + (y - z))) / 4;
}
console.log(stableHeron(...needle));                 // 5000
console.log(stableHeron(7, 8, 9) === heron(7, 8, 9)); // true

Here x - y is a billion minus a billion, which is exactly 0, so nothing is lost. The algebra is the same as Heron's, and it returns 5000 exactly. On an ordinary triangle like 7-8-9 both versions agree to the last digit.

The full solution

The answer panel has byBaseHeight, heron and stableHeron, and prints the 3-4-5 triangle both ways, the 7-8-9 and equilateral triangles, the flat and impossible ones, and the needle with Heron, the stable version, the true area and the relative error. Press Run to see the output.

The answer

const byBaseHeight = (base, height) => 0.5 * base * height;

const heron = (a, b, c) => {
  const s = (a + b + c) / 2;
  return Math.sqrt(s * (s - a) * (s - b) * (s - c));
};

// Kahan's rearrangement: sort descending, then group so nothing nearly cancels.
function stableHeron(a, b, c) {
  const [x, y, z] = [a, b, c].sort((p, q) => q - p);
  return Math.sqrt((x + (y + z)) * (z - (x - y)) * (z + (x - y)) * (x + (y - z))) / 4;
}

// A needle: two sides of a billion, one of a hundred-thousandth.
const needle = [1e9, 1e9, 1e-5];
const trueArea = 0.5 * 1e-5 * 1e9;          // base times height, to the last digit
const relativeError = (heron(...needle) - trueArea) / trueArea;

console.log('base 4, height 3 :', byBaseHeight(4, 3), 'Heron on 3-4-5:', heron(3, 4, 5));
console.log('7-8-9            :', heron(7, 8, 9), stableHeron(7, 8, 9));
console.log('equilateral, 2   :', heron(2, 2, 2), 'which is sqrt(3):', Math.sqrt(3));
console.log('1-2-3, degenerate:', heron(1, 2, 3));
console.log('1-2-10, no such  :', heron(1, 2, 10));
console.log('needle, Heron    :', heron(...needle));
console.log('needle, stable   :', stableHeron(...needle), 'true', trueArea);
console.log('relative error   :', relativeError);

Output


      
8 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 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('half base times height and Heron agree on the 3-4-5 triangle', [byBaseHeight(4, 3), heron(3, 4, 5)], [6, 6]);
test('and agree to the last bit on a 7-8-9 triangle', [heron(7, 8, 9), heron(7, 8, 9) === stableHeron(7, 8, 9)], [26.832815729997478, true]);
test('an equilateral triangle of side 2 has area exactly sqrt(3)', heron(2, 2, 2) === Math.sqrt(3), true);
test('1, 2, 3 is three collinear points, and Heron returns a clean 0', heron(1, 2, 3), 0);
test('1, 2, 10 breaks the triangle inequality, so the root goes negative', Number.isNaN(heron(1, 2, 10)), true);
test('on a needle triangle the true area is 5000 and Heron says 5006.79', [trueArea, heron(...needle)], [5000, 5006.7901611328125]);
test('that is 0.14 per cent out, from digits cancelling in s - a', Math.round(relativeError * 1e6) / 1e6, 0.001358);
test('the rearranged formula returns 5000 exactly', stableHeron(...needle), 5000);

Heron's formula is correct and, written the obvious way, numerically fragile. For a needle triangle the semi-perimeter s is almost exactly the longest side, so s - a subtracts two nearly equal numbers and most of the significant digits cancel; what is left is rounding noise, multiplied by the other three large factors. Here that puts the answer 0.14% out — not a rounding wobble in the last bit, a visibly wrong number.

Kahan's rearrangement sorts the sides descending and groups the factors as (a + (b + c))(c - (a - b))(c + (a - b))(a + (b - c)), which never subtracts two nearly equal large values, and it returns 5000 exactly. Same algebra, different arithmetic. The other two edges are worth knowing too: three collinear lengths give exactly 0, and lengths that violate the triangle inequality give a negative product and therefore NaN — so check for NaN rather than assuming a number came back.

Common mistakes

  • Using the full perimeter instead of half. s is (a + b + c) / 2. Without the / 2 the answer is far too big.
  • Not checking for NaN. Sides that break the triangle rule give NaN, not an error.
  • Trusting Heron on very thin triangles. Nearly equal numbers cancel in s - a. Use the sorted, regrouped version.

Try it yourself

  1. Find the area of a triangle with sides 13, 14 and 15 with both heron and stableHeron.
  2. Write isTriangle(a, b, c) that returns true only when each side is shorter than the other two together.
  3. Try heron and stableHeron on [1e8, 1e8, 1e-4]. What should the area be?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.