Newton's method square root in JavaScript
Intermediate · 4 min read
How do you find a square root without a square root button? Guess, then improve the guess. If your guess for the square root of 2 is 1, then 2 / 1 = 2 is too big, so the true root lies between 1 and 2. Take the average, 1.5, and repeat. This is Heron's method, nearly two thousand years old, and it is a special case of Newton's method, the standard way computers solve equations by improving a guess.
In this tutorial you will write the method, watch how fast it gets close, and compare it with JavaScript's own Math.sqrt. You will also meet the two traps that catch most people: a stopping rule that never stops, and inputs the method was never meant to handle. You need to know loops and functions.
One step of the method
If x is a guess for the square root of n, then x and n / x sit on either side of the true root. Their average is a better guess:
const step = (x, n) => (x + n / x) / 2;
console.log(step(1, 2), step(1.5, 2)); // 1.5 1.4166666666666665
That one line is the whole algorithm. Everything else is deciding where to start and when to stop.
How fast it closes in
The error is how far the guess is from the true root. With this method, each new error is roughly the old error squared (divided by twice the root). An error of 0.01 becomes about 0.0001, then 0.00000001. The number of correct digits roughly doubles every step. This is called quadratic convergence.
Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.
109 Newton's method for a square root, against Math.sqrt
fairImplement Heron's iteration — x = (x + n / x) / 2 — and watch the error square itself at every step. Then compare its answer with Math.sqrt over the first ten thousand integers, count how often the two agree bit for bit, and find the stopping rule that never terminates.
Stuck? Three hints, smallest first
- 1. Each step roughly doubles the number of correct digits, so five or six are enough from a sensible starting guess.
- 2. Stopping when
Math.abs(x * x - n) < 1e-10is unusable for large n: at that scale the residual can never get that small. - 3. The iteration ends up alternating between two adjacent doubles, so stop when the next value repeats either of the last two.
Step 1: watch five steps
const trace = [1];
for (let i = 0; i < 5; i++) trace.push(step(trace[trace.length - 1], 2));
console.log(trace.join(' ')); // 1 1.5 1.4166666666666665 1.4142156862745097 1.4142135623746899 1.414213562373095
const errors = trace.map((x) => x - Math.sqrt(2));
console.log(errors[2], errors[3], errors[4]); // 0.002453104293571373 0.000002123901414519125 1.5947243525715749e-12
Look at the errors: about 0.0025, then 0.0000021, then 0.0000000000016. Each one has roughly twice as many zeros as the one before.
Step 2: stop when the value stops moving
In double arithmetic, the guess eventually stops changing, or flips back and forth between two neighboring values. Either one is the signal to stop.
function heron(n) {
if (n < 0) return { root: NaN, steps: 0 };
if (n === 0) return { root: 0, steps: 0 };
let x = n;
let prev = -1;
let steps = 0;
while (steps < 100) {
const next = step(x, n);
steps++;
if (next === x || next === prev) return { root: Math.min(x, next), steps };
prev = x;
x = next;
}
return { root: x, steps };
}
console.log(heron(2).root, heron(2).steps, Math.sqrt(2)); // 1.414213562373095 6 1.4142135623730951
The function starts from x = n, keeps the previous guess in prev, and returns an object with the root and the number of steps. When the value repeats or flips, it returns the smaller of the two. The cap of 100 steps means the loop always ends.
The answer is one tiny step below Math.sqrt(2): they differ in the last digit.
Step 3: compare with Math.sqrt
let identical = 0;
for (let n = 1; n <= 10000; n++) if (heron(n).root === Math.sqrt(n)) identical++;
console.log(identical); // 7565
Over the first ten thousand whole numbers, the two agree exactly 7565 times, and every other time they differ by the smallest possible amount. That isn't sloppiness. The standard that defines JavaScript numbers requires Math.sqrt to give the closest possible double to the true root. Heron's method rounds at every step, so it can end one double away. In real code, use Math.sqrt.
Step 4: a better starting guess
Starting at n itself is a poor guess for big numbers. 2 ** Math.round(Math.log2(n) / 2) is a power of two close to the root, and the answer's heronGuessed is heron started from it.
console.log(heron(1e10).steps, 2 ** Math.round(Math.log2(1e10) / 2)); // 22 131072
The true root of 1e10 is 100000, and 131072 is close. From that start, the method needs 6 steps instead of 22.
Step 5: the wrong turn, a fixed tolerance
A textbook stopping rule is "stop when x * x is within 1e-10 of n". It looks sensible:
function stepsUntilAbsolute(n, cap) {
let x = n;
let steps = 0;
while (Math.abs(x * x - n) > 1e-10 && steps < cap) { x = step(x, n); steps++; }
return steps;
}
console.log(stepsUntilAbsolute(2, 500), stepsUntilAbsolute(2e20, 500)); // 4 500
For 2 it stops after 4 steps. For 2e20 it uses all 500 steps the cap allows. Doubles near 2e20 are 32768 apart, so x * x - n can never get as small as 1e-10. Without the cap, this loop would run forever.
Step 6: a tolerance that scales
function stepsUntilRelative(n, cap) {
let x = n;
let steps = 0;
while (Math.abs(x * x - n) > n * Number.EPSILON && steps < cap) { x = step(x, n); steps++; }
return steps;
}
console.log(stepsUntilRelative(2e20, 500)); // 38
Number.EPSILON is the gap between 1 and the next double, about 2.2e-16. Multiplying it by n makes the tolerance grow with the number, and now 2e20 stops after 38 steps.
Step 7: guard the input
function unguarded(n, steps) {
let x = n;
for (let i = 0; i < steps; i++) x = step(x, n);
return x;
}
console.log(unguarded(0, 5), unguarded(-4, 5), Math.sqrt(-4)); // NaN 1.6830612052619665 NaN
With 0, the first step divides 0 by 0, which is NaN. With -4, the method wanders and returns a normal-looking positive number that isn't the square root of anything. That is why heron checks for negative numbers and 0 before it starts.
The full solution
The answer panel has step, heron, heronGuessed, both stopping rules and the unguarded version, and also checks that each error matches the "square of the last one" prediction. Press Run to see the output.
const step = (x, n) => (x + n / x) / 2;
// Iterate until the value stops changing, or repeats the one before it.
function heron(n) {
if (n < 0) return { root: NaN, steps: 0 };
if (n === 0) return { root: 0, steps: 0 };
let x = n;
let prev = -1;
let steps = 0;
while (steps < 100) {
const next = step(x, n);
steps++;
if (next === x || next === prev) return { root: Math.min(x, next), steps };
prev = x;
x = next;
}
return { root: x, steps };
}
// Same iteration, started from a power of two near the root.
function heronGuessed(n) {
if (n <= 0) return heron(n);
let x = 2 ** Math.round(Math.log2(n) / 2);
let prev = -1;
let steps = 0;
while (steps < 100) {
const next = step(x, n);
steps++;
if (next === x || next === prev) return { root: Math.min(x, next), steps };
prev = x;
x = next;
}
return { root: x, steps };
}
// Two stopping rules, both capped so a panel cannot hang.
function stepsUntilAbsolute(n, cap) {
let x = n;
let steps = 0;
while (Math.abs(x * x - n) > 1e-10 && steps < cap) { x = step(x, n); steps++; }
return steps;
}
function stepsUntilRelative(n, cap) {
let x = n;
let steps = 0;
while (Math.abs(x * x - n) > n * Number.EPSILON && steps < cap) { x = step(x, n); steps++; }
return steps;
}
// No guard at all: five steps, whatever the input.
function unguarded(n, steps) {
let x = n;
for (let i = 0; i < steps; i++) x = step(x, n);
return x;
}
const trace = [1];
for (let i = 0; i < 5; i++) trace.push(step(trace[trace.length - 1], 2));
const errors = trace.map((x) => x - Math.sqrt(2));
// Quadratic convergence says the next error is about the square of this one,
// divided by twice the root.
const predicted = errors[3] ** 2 / (2 * Math.sqrt(2));
let identical = 0;
let worstGap = 0;
for (let n = 1; n <= 10000; n++) {
const mine = heron(n).root;
const theirs = Math.sqrt(n);
if (mine === theirs) identical++;
const gap = Math.abs(mine - theirs) / theirs / Number.EPSILON;
if (gap > worstGap) worstGap = gap;
}
console.log('trace from 1 :', trace);
console.log('errors :', errors);
console.log('predicted 5th :', predicted, 'actual', errors[4]);
console.log('heron(2) :', heron(2).root, 'in', heron(2).steps, 'steps, against', Math.sqrt(2));
console.log('steps, 1e10 :', heron(1e10).steps, 'with a guess', heronGuessed(1e10).steps);
console.log('bit identical :', identical, 'of 10000, worst gap', worstGap, 'x EPSILON');
console.log('absolute rule :', stepsUntilAbsolute(2e20, 500), 'steps (capped at 500)');
console.log('relative rule :', stepsUntilRelative(2e20, 500), 'steps');
console.log('unguarded 0 :', unguarded(0, 5), 'and -4 gives', unguarded(-4, 5));
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('five steps from 1 walk 2 down to 1.414213562373095', trace, [1, 1.5, 1.4166666666666665, 1.4142156862745097, 1.4142135623746899, 1.414213562373095]);
test('the error squares each time: 0.0857, 0.00245, 2.1e-6, 1.6e-12', errors.slice(1, 5), [0.08578643762690485, 0.002453104293571373, 0.000002123901414519125, 1.5947243525715749e-12]);
test('and the predicted next error is within a hundredth of a percent of the real one', Math.abs(predicted / errors[4] - 1) < 0.001, true);
test('it settles one part in 2 ** 52 below Math.sqrt(2), in six steps', [heron(2).root, heron(2).steps, heron(2).root === Math.sqrt(2)], [1.414213562373095, 6, false]);
test('over 1..10000 it matches Math.sqrt bit for bit 7565 times out of 10000', identical, 7565);
test('and is never off by more than a relative Number.EPSILON', worstGap < 1, true);
test('starting from a power of two near the root cuts 22 steps to 6', [heron(1e10).steps, heronGuessed(1e10).steps], [22, 6]);
test('an absolute tolerance never terminates for 2e20, where a relative one takes 38', [stepsUntilAbsolute(2e20, 500), stepsUntilRelative(2e20, 500)], [500, 38]);
test('and with no guard, 0 gives NaN while -4 gives a confident 1.6830612052619665', [Number.isNaN(unguarded(0, 5)), unguarded(-4, 5), Number.isNaN(Math.sqrt(-4))], [true, 1.6830612052619665, true]);
Heron's iteration is the oldest algorithm most people ever write, and its convergence is the thing to see: from a start of 1, the errors run 0.086, 0.0025, 2.1e-6, 1.6e-12. Each is about the square of the last divided by twice the root, which is what quadratic convergence means — the number of correct digits doubles per step. Six steps is not a coincidence of this example; it is what quadratic convergence buys you from any starting point within a factor of two, which is why the version seeded with 2 ** round(log2(n) / 2) needs 6 steps for 1e10 where starting from n itself needs 22.
It does not, however, reproduce Math.sqrt. Over the first ten thousand integers the two agree bit for bit 7565 times and differ by a bit the rest. Neither is sloppy: IEEE-754 requires sqrt to be correctly rounded, meaning within half a bit of the true root, and hardware delivers that; Heron's iteration in double arithmetic gets within one bit and no better, because each step rounds. So Math.sqrt is the right answer in production, and this exercise is about why it is worth understanding what it does.
The two traps are stopping and the domain. Math.abs(x * x - n) < 1e-10 is the textbook rule and it is unusable: at n = 2e20 the residual bottoms out around 32768, so the loop spins forever — this panel only survives it because the count is capped at 500. Scale the tolerance to n, or stop when the value stops moving. And the iteration has no idea what its domain is: n = 0 divides by zero and gives NaN, while n = -4 wanders off and returns 1.6830612052619665, a perfectly finite positive number that is not a square root of anything. Math.sqrt(-4) says NaN. Guard the input before you iterate.
Common mistakes
- Stopping on a fixed tolerance like 1e-10. For big inputs it is never reached. Scale it with
n, or stop when the value stops changing. - Writing a loop with no step limit. If the stopping rule is wrong, the page hangs.
- Skipping the input checks. A negative input returns a wrong number instead of
NaN.
Try it yourself
- Change
stepto find cube roots:(2 * x + n / (x * x)) / 3. Test it on 27. - Print how many steps
heronGuessedneeds for 1, 1e5, 1e10 and 1e15. - Find the first whole number where
heron(n).rootandMath.sqrt(n)disagree.