Emmanuel Akinfulubi

JavaScriptMath

Solve a quadratic equation in JavaScript

Advanced · 4 min read

A quadratic equation looks like ax² + bx + c = 0. Its solutions, called roots, are the values of x that make it true. Quadratics turn up when you work out where a thrown ball lands, when two moving things meet, and in lots of geometry. Most people learn one formula for them at school, and it works on paper every time.

In code, it doesn't. In this tutorial you will write the school formula, then give it an equation where it gets one root a quarter of the way wrong. You will learn why (it is called catastrophic cancellation), write the version numerical programmers use, and prove which is right by putting the roots back into the equation. Then you will handle the edge cases: no real roots, a = 0, and numbers so big they overflow. You need to know functions, arrays and Math.sqrt.

The school formula

The roots are (-b + √d) / 2a and (-b - √d) / 2a, where d = b² - 4ac is the discriminant. If d is positive there are two roots, if it is 0 there is one (twice), and if it is negative there are no real roots.

Checking an answer: the residual

To check a root, put it back into the equation and see how far from 0 you land. That leftover is called the residual. It is the one check that doesn't need you to know the answer already.

JavaScript

const residual = (a, b, c, x) => a * x * x + b * x + c;
console.log(residual(1, -5, 6, 2), residual(1, -5, 6, 4)); // 0 2

x = 2 solves x² - 5x + 6 = 0. x = 4 doesn't.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

112 Quadratic roots, written so they survive

hard

Solve a quadratic with the formula you were taught, then solve x² + 100000000x + 1 = 0 with it and check the roots by substituting them back. Write the stable version, compare residuals, and say what each version does when the discriminant is negative, when a is zero, and when b² overflows.

Stuck? Three hints, smallest first
  1. 1. The two roots come out of (-b ± sqrt(d)) / (2a), and when b is huge one of those is a big number minus a nearly equal big number.
  2. 2. Compute the root that does not cancel, then get the other from the fact that the roots multiply to c / a.
  3. 3. Substituting a root back in and seeing how far from zero you land is the only honest test of a solver.

Step 1: the formula as taught

Step 1

function naiveRoots(a, b, c) {
  const d = b * b - 4 * a * c;
  const root = Math.sqrt(d);
  return [(-b + root) / (2 * a), (-b - root) / (2 * a)];
}
console.log(naiveRoots(1, -5, 6), naiveRoots(1, -2, 1)); // [ 3, 2 ] [ 1, 1 ]

With friendly numbers it is exactly right. x² - 2x + 1 has a discriminant of 0, so the same root comes out twice.

Step 2: the wrong turn, a huge b

Now try x² + 100000000x + 1 = 0. Its roots are close to -100000000 and -0.00000001.

Step 2

const naiveBig = naiveRoots(1, 1e8, 1);
console.log(naiveBig[0]);                     // -7.450580596923828e-9
console.log(residual(1, 1e8, 1, naiveBig[0])); // 0.2549419403076172

The small root should be about -1e-8, but the formula says -7.45e-9, roughly a quarter off. Putting it back in leaves 0.25 instead of 0.

Why it goes wrong

Here √d is 99999999.99999999, almost exactly b. The small root is -b + √d: one huge number minus another nearly equal one. Both carry about 16 correct digits, and they share almost all of them, so subtracting wipes those digits out and leaves mostly rounding error. That is catastrophic cancellation.

JavaScript

console.log(-1e8 + Math.sqrt(1e8 * 1e8 - 4)); // -1.4901161193847656e-8

The true answer to that subtraction is about -2e-8. Only rounding error is left.

Step 3: the stable formula

The other root, -b - √d, adds two numbers of the same sign, so nothing cancels. Compute that one safely, and get the second root from a fact about quadratics: the two roots multiply to c / a.

Step 3

function stableRoots(a, b, c) {
  const d = b * b - 4 * a * c;
  if (d < 0) return [];
  const root = Math.sqrt(d);
  const q = -(b + Math.sign(b || 1) * root) / 2;
  return [q / a, q === 0 ? 0 : c / q];
}
const stableBig = stableRoots(1, 1e8, 1);
console.log(stableBig);                          // [ -100000000, -1e-8 ]
console.log(residual(1, 1e8, 1, stableBig[1]));  // 1.1102230246251565e-16

Math.sign(b) is 1 or -1, so b + sign(b) * root always adds two same-signed numbers. When b is 0, b || 1 uses 1 instead, because Math.sign(0) is 0. The first root is q / a, and the second is c / q.

The residual drops from 0.25 to about 0.0000000000000001. Same equation, same numbers, a different order of operations.

Step 4: no real roots

Step 4

console.log(naiveRoots(1, 1, 1), stableRoots(1, 1, 1)); // [ NaN, NaN ] []

x² + x + 1 has a negative discriminant. Math.sqrt of a negative number is NaN, and the school version passes those along to whatever comes next. The stable version returns an empty list, which the caller can check with .length.

Step 5: when a is zero

Step 5

console.log(naiveRoots(0, 2, -4), stableRoots(0, 2, -4)); // [ NaN, -Infinity ] [ -Infinity, 2 ]

With a = 0, the equation is really 2x - 4 = 0, whose answer is 2. The school version divides by 2 * a, which is 0, and gets nonsense. The stable version still finds 2, because c / q never uses a. Its first root is still nonsense, so real code should check for a === 0 and solve the straight line separately.

Step 6: numbers too big to square

Step 6

function scaledRoots(a, b, c) {
  const s = Math.max(Math.abs(a), Math.abs(b), Math.abs(c));
  return stableRoots(a / s, b / s, c / s);
}
console.log(1e200 * 1e200, naiveRoots(1, 1e200, 1)[0]); // Infinity Infinity
console.log(scaledRoots(1, 1e200, 1));                  // [ -1e+200, -1e-200 ]

b * b is 1e400, bigger than the largest double, so it becomes Infinity before anything else happens. Dividing all three numbers by the biggest one gives the same equation with smaller numbers, and the roots come back right.

The full solution

The answer panel has residual, naiveRoots, stableRoots and scaledRoots, and also checks the product of the roots for both versions and what the school formula does with b = 1e9. Press Run to see the output.

The answer

const residual = (a, b, c, x) => a * x * x + b * x + c;

// The formula as taught.
function naiveRoots(a, b, c) {
  const d = b * b - 4 * a * c;
  const root = Math.sqrt(d);
  return [(-b + root) / (2 * a), (-b - root) / (2 * a)];
}

// The stable formula. Add the square root to b with b's own sign, so nothing
// cancels, then get the second root from the product of the roots, c / a.
function stableRoots(a, b, c) {
  const d = b * b - 4 * a * c;
  if (d < 0) return [];
  const root = Math.sqrt(d);
  const q = -(b + Math.sign(b || 1) * root) / 2;
  return [q / a, q === 0 ? 0 : c / q];
}

// Divide through by the largest coefficient first, so b * b cannot overflow.
function scaledRoots(a, b, c) {
  const s = Math.max(Math.abs(a), Math.abs(b), Math.abs(c));
  return stableRoots(a / s, b / s, c / s);
}

const naiveBig = naiveRoots(1, 1e8, 1);
const stableBig = stableRoots(1, 1e8, 1);
const naiveResiduals = naiveBig.map((x) => residual(1, 1e8, 1, x));
const stableResiduals = stableBig.map((x) => residual(1, 1e8, 1, x));

// Vieta: the roots must add to -b / a and multiply to c / a.
const vietaNaive = naiveBig[0] * naiveBig[1] - 1;
const vietaStable = stableBig[0] * stableBig[1] - 1;

const overflowed = naiveRoots(1, 1e200, 1);
const stableOverflowed = stableRoots(1, 1e200, 1);
const rescued = scaledRoots(1, 1e200, 1);

console.log('x2 - 5x + 6      :', naiveRoots(1, -5, 6), stableRoots(1, -5, 6));
console.log('x2 - 2x + 1      :', naiveRoots(1, -2, 1), 'discriminant', 4 - 4);
console.log('x2 + x + 1       :', naiveRoots(1, 1, 1), 'against a list of', stableRoots(1, 1, 1).length, 'real roots');
console.log('b = 1e8, naive   :', naiveBig, 'residuals', naiveResiduals);
console.log('b = 1e8, stable  :', stableBig, 'residuals', stableResiduals);
console.log('b = 1e9, naive   :', naiveRoots(1, 1e9, 1), '<- the small root is gone');
console.log('a = 0, naive     :', naiveRoots(0, 2, -4), 'stable', stableRoots(0, 2, -4));
console.log('b = 1e200        :', overflowed, 'discriminant', 1e200 * 1e200);
console.log('stable, scaled   :', stableOverflowed, rescued);

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.

9 checks

test('with friendly numbers both versions agree, exactly', [naiveRoots(1, -5, 6), stableRoots(1, -5, 6)], [[3, 2], [3, 2]]);
test('a zero discriminant gives the same root twice', [naiveRoots(1, -2, 1), (-2) ** 2 - 4], [[1, 1], 0]);
test('a negative one gives two NaNs, where the stable version reports no real roots', [naiveRoots(1, 1, 1).map(Number.isNaN), stableRoots(1, 1, 1)], [[true, true], []]);
test('for b = 1e8 the taught formula loses a quarter of the small root', [naiveBig[0], stableBig[1]], [-7.450580596923828e-9, -1e-8]);
test('substituting back proves it: 0.25 against 1.1e-16', [naiveResiduals[0], stableResiduals[1]], [0.2549419403076172, 1.1102230246251565e-16]);
test('and the product of the roots should be exactly c / a, which is 1', [vietaNaive, vietaStable], [-0.2549419403076172, 0]);
test('one more decade and the small root collapses to exactly zero', naiveRoots(1, 1e9, 1)[0], 0);
test('with a = 0 the taught formula gives NaN and -Infinity, while the stable one finds x = 2', [Number.isNaN(naiveRoots(0, 2, -4)[0]), naiveRoots(0, 2, -4)[1] === -Infinity, stableRoots(0, 2, -4)[1]], [true, true, 2]);
test('and b = 1e200 overflows the discriminant, until you scale the coefficients first', [overflowed[0] === Infinity, Object.is(stableOverflowed[1], -0), rescued], [true, true, [-1e200, -1e-200]]);

Exercise 28 pointed here. x² + 100000000x + 1 = 0 has roots near -1e-8 and -1e8, and the formula everyone memorised returns -7.450580596923828e-9 for the small one — a quarter of the way wrong. Nothing is broken: -b + Math.sqrt(d) is 1e8 minus 99999999.99999998, two nearly equal numbers, and subtracting them throws away every significant digit they had in common. This is catastrophic cancellation, and it is the reason numerical analysis exists as a subject.

The fix costs one line. Compute q = -(b + sign(b) * sqrt(d)) / 2, which adds two same-signed numbers so nothing cancels, take q / a as the safe root, and get the other from the fact that the roots multiply to c / a. Substituting back is what proves it: the taught version leaves a residual of 0.25, the stable one 1.1e-16. Any solver you write should be checked this way, because a residual is the only test that does not need to know the answer in advance.

Then the edges, and they all pass in silence. A negative discriminant makes Math.sqrt return NaN, so the taught version hands back two NaNs that will propagate through everything downstream; returning an empty list says the same thing in a form the caller can test. a = 0 is not a quadratic at all, and dividing by 2 * a gives NaN and -Infinity — while the stable form, oddly, still finds the linear root 2, because c / q never touches a. And b = 1e200 overflows b * b to Infinity before the discriminant is even finished, which the stable version reports as a -0 root; dividing all three coefficients by the largest of them first brings the whole thing back into range and recovers -1e200 and -1e-200.

Common mistakes

  • Trusting the school formula in code. When b is much bigger than a and c, the small root loses most of its digits.
  • Returning NaN for "no roots". Return an empty list, or something else the caller can test.
  • Not checking the answer. Put each root back into the equation and look at the residual.

Try it yourself

  1. Compare naiveRoots and stableRoots on x² - 1e8x + 1 = 0, with a negative b.
  2. Add a check to stableRoots so that a === 0 returns the single root -c / b.
  3. Write vietaCheck(a, b, c, roots) that checks the roots add to -b / a and multiply to c / a.

Keep practising

Newsletter

New writing, when it lands.

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