Fix floating-point errors in a loop in JavaScript
Intermediate · 4 min read
One tiny floating-point error is harmless. A loop that adds a decimal over and over is different: every addition rounds a little, and the roundings pile up. Running totals, game timers that add 0.1 seconds per tick, and animation counters all do this.
In this tutorial you will add 0.1 to a total ten times and a hundred times, watch the error grow, and then fix it two ways: by counting in whole numbers, and with a clever technique called Kahan summation. You need to know for loops and how to write a function.
Why errors grow in a loop
0.1 can't be stored exactly in binary, so JavaScript keeps the closest value it can. Each time you add it to a total, the new total also has to be rounded to the closest storable value. One rounding is a tiny error. A hundred roundings are a hundred tiny errors, and they don't cancel out neatly.
The fix is to do fewer roundings, or to keep track of what each rounding threw away.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
14 Error accumulating over a loop
fairAdd 0.1 to a running total ten times and a hundred times. Then fix it twice: once by counting in integers, once with compensated summation.
Stuck? Three hints, smallest first
- 1. Ten additions leave the total just under 1; a hundred leave it further out.
- 2. Counting integers and dividing once at the end has no accumulation at all.
- 3. Kahan summation keeps a separate running record of the bits that were dropped.
Step 1: add a tenth ten times
let ten = 0;
for (let i = 0; i < 10; i++) ten += 0.1;
console.log(ten); // 0.9999999999999999
console.log(ten === 1); // false
ten += 0.1 is short for ten = ten + 0.1. After ten additions you are just short of 1.
Step 2: a hundred times
let hundred = 0;
for (let i = 0; i < 100; i++) hundred += 0.1;
console.log(hundred); // 9.99999999999998
The answer should be 10. The error is now in the 14th decimal place instead of the 16th: about a hundred times bigger. The longer the loop, the further the total drifts.
Step 3: a loop that never stops
The same problem breaks loop conditions. This loop waits for x to equal exactly 1:
let x = 0;
let n = 0;
while (x !== 1 && n < 20) {
x += 0.1;
n++;
}
console.log(n); // 20
x jumps from 0.9999999999999999 straight past 1 without ever equaling it. Without the n < 20 safety limit, this would run forever. That is why it's in there.
Step 4: fix one, count in whole numbers
Whole numbers are stored exactly, so counting with them has no error at all. Count tenths as integers, and divide once at the very end:
const tenths = (count) => count / 10;
console.log(tenths(10)); // 1
console.log(tenths(100)); // 10
console.log(0.1 * 10 === 1); // true
There is now one rounding instead of a hundred. The same goes for loops: loop over a whole number i, and work out the decimal inside with i / 10.
for (let i = 0; i <= 3; i++) console.log(i / 10); // 0, 0.1, 0.2, 0.3 on four lines
Step 5: fix two, Kahan summation
Sometimes you can't avoid adding decimals, for example when summing a list of measurements. Kahan summation (named after William Kahan, who designed it) keeps a second variable, c, that records the small part each addition lost, and adds it back on the next round.
function kahan(xs) {
let sum = 0;
let c = 0;
for (const x of xs) {
const y = x - c;
const t = sum + y;
c = t - sum - y;
sum = t;
}
return sum;
}
console.log(kahan(new Array(10).fill(0.1))); // 1
console.log(kahan(new Array(100).fill(0.1))); // 10
Read the loop body slowly:
y = x - ccorrects the next value by the error carried from last time.t = sum + yis the new total, rounded as usual.t - sumis how much the total really went up. Subtractingy, what we meant to add, leaves exactly the bit that rounding lost. That goes intoc.sum = tmoves on.
new Array(10).fill(0.1) makes an array of ten 0.1s to test with.
Kahan summation costs a few extra operations per item, and it stops errors from building up. It can't make 0.1 a perfect tenth, but here the leftover error is too small to show.
The full solution
The answer panel runs both loops, the integer fix, Kahan summation, and the while loop with its safety limit. The checks underneath confirm each total, including that the loop waiting for exactly 1 hits its limit of 20. Press Run to see the output.
let ten = 0;
for (let i = 0; i < 10; i++) ten += 0.1;
let hundred = 0;
for (let i = 0; i < 100; i++) hundred += 0.1;
// Fix one: count in integers, divide once.
const tenths = (count) => count / 10;
// Fix two: Kahan summation. `c` carries the low-order bits that were lost.
function kahan(xs) {
let sum = 0;
let c = 0;
for (const x of xs) {
const y = x - c;
const t = sum + y;
c = t - sum - y;
sum = t;
}
return sum;
}
// A float loop counter that tests for equality may never stop, so this one is bounded.
const steps = (() => {
let x = 0;
let n = 0;
while (x !== 1 && n < 20) { x += 0.1; n++; }
return n;
})();
console.log('ten additions :', ten, ' === 1?', ten === 1);
console.log('hundred additions:', hundred);
console.log('integers instead :', tenths(10), tenths(100));
console.log('kahan :', kahan(new Array(10).fill(0.1)));
console.log('a while (x !== 1) loop ran', steps, 'times without ever hitting 1');
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.
test('adding a tenth ten times does not reach 1', ten === 1, false);
test('it stops just short', ten, 0.9999999999999999);
test('a hundred times, the error is larger', hundred, 9.99999999999998);
test('counting integers and dividing once is exact', [tenths(10), tenths(100)], [1, 10]);
test('so is multiplying instead of accumulating', 0.1 * 10 === 1, true);
test('compensated summation recovers the 1', kahan(new Array(10).fill(0.1)), 1);
test('and the 10', kahan(new Array(100).fill(0.1)), 10);
test('a loop that waits for exactly 1 never gets there', steps, 20);
Error does not stay put: each addition rounds, and the roundings compound. Over a hundred additions the total is out by 2e-14, which is invisible until it is a balance sheet.
The integer fix is the one to reach for. Loop over i, derive the value as i / 10, and there is one rounding rather than a hundred. The same rule governs loop conditions: for (let x = 0; x !== 1; x += 0.1) is an infinite loop, and even x < 1 runs a different number of times than you counted. Loop over integers and scale inside the body.
Kahan summation is worth knowing exists. It costs three extra operations per element and recovers most of the lost precision, which is why numerical libraries use it for long sums. It is not magic — it cannot fix 0.1 not being a tenth — it only stops the accumulation of that error.
Common mistakes
- Writing
for (let x = 0; x !== 1; x += 0.1). It never stops. Loop over whole numbers and divide inside the body. - Comparing a running total with
===. After a loop of decimals, compare with a tolerance, or keep the total in whole units. - Assuming
x < 1fixes the loop. It stops, but it runs one more time than you counted, because 0.9999999999999999 is still less than 1.
Try it yourself
- Count how many times
for (let x = 0; x < 1; x += 0.1)runs. Is it 10? - Add 0.01 a thousand times with
+=, then withkahan. Compare both with 10. - Rewrite a timer that adds 0.1 seconds per tick so it counts ticks as whole numbers instead.