Emmanuel Akinfulubi

JavaScriptMath

Kahan summation in JavaScript

Advanced · 4 min read

Add 0.1 to itself a hundred thousand times and you should get exactly 10000. A plain loop gives 10000.000000018848. Each addition rounds a tiny amount, and over a long list those tiny amounts pile up. This matters anywhere you total a long column of numbers: sensor readings, statistics, physics simulations, totals in a spreadsheet.

In this tutorial you will learn four ways to add a list: straight through, with Kahan summation, with Neumaier's improvement on it, and pairwise. You will measure each one against an exact answer, and then find a short list where Kahan gets it completely wrong. You need to know loops, reduce and a little about why 0.1 isn't stored exactly.

Why additions lose bits

A double keeps about 16 significant digits. When you add a small number to a big one, the result is rounded to those 16 digits, and the lowest digits of the small number are dropped. One dropped digit is nothing. A hundred thousand of them add up to an error you can see.

JavaScript

console.log(1e16 + 1); // 10000000000000000

The + 1 is too small to show at this size, so it is lost completely.

The idea behind compensation

Kahan's trick is to work out what each addition dropped and keep it in a second variable, often called c for "compensation". The next time round, that lost amount is added back in.

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

107 Compensated summation, and where Kahan itself fails

hard

Add a hundred thousand tenths four ways: straight through, with Kahan compensation, with Neumaier's improvement, and pairwise. Check each against a reference computed in exact integer arithmetic. Then find the four-element list where Kahan summation gets the answer wrong and Neumaier does not.

Stuck? Three hints, smallest first
  1. 1. Kahan keeps a second variable holding the low-order bits the last addition dropped, and subtracts it from the next term.
  2. 2. Pairwise summation needs no compensation at all: it just adds halves of halves, so the error grows like log n rather than n.
  3. 3. Kahan assumes the running total is the larger of the two operands. Feed it a term far bigger than the total so far and the correction is computed from the wrong end.

Step 1: the plain sum

Step 1

const naive = (xs) => xs.reduce((a, b) => a + b, 0);
const N = 100000;
const tenths = new Array(N).fill(0.1);
console.log(naive(tenths)); // 10000.000000018848

new Array(N).fill(0.1) makes a list of a hundred thousand tenths. The total overshoots 10000.

Step 2: Kahan summation

Step 2

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(tenths)); // 10000

Read the middle of the loop slowly:

  • y = x - c is the next term, corrected by what the last addition lost.
  • t = sum + y is the new total, rounded as usual.
  • t - sum is how much the total actually went up. Subtract y, what it should have gone up by, and you get the rounding error. That becomes the new c.

The result is exactly 10000.

Step 3: pairwise summation

Another way avoids the extra variable altogether. Split the list in half, add up each half, and add the two results. Each half is split again, until the pieces are small.

Step 3

function pairwise(xs, lo, hi) {
  const from = lo === undefined ? 0 : lo;
  const to = hi === undefined ? xs.length : hi;
  if (to - from <= 8) {
    let s = 0;
    for (let i = from; i < to; i++) s += xs[i];
    return s;
  }
  const mid = (from + to) >> 1;
  return pairwise(xs, from, mid) + pairwise(xs, mid, to);
}
console.log(pairwise(tenths)); // 10000

lo and hi mark the part of the list to add, and the first call leaves them out. >> 1 halves a whole number. In a straight loop, the first number goes through 100000 additions. Here, the list is split about 14 times before the pieces are small, so each number passes through only a couple of dozen additions, and far less error builds up.

Step 4: an exact reference

To score the methods properly, you need the true answer. The harmonic sum, 1 + 1/2 + 1/3 + ... + 1/100000, can be worked out exactly with BigInt by scaling every term up by 10 to the 30:

Step 4

const harmonic = Array.from({ length: N }, (_, i) => 1 / (i + 1));
const SCALE = 10n ** 30n;
let scaled = 0n;
for (let k = 1n; k <= BigInt(N); k++) scaled += SCALE / k;
const reference = Number(scaled) / 1e30;
console.log(reference); // 12.090146129863427

Every term keeps 30 decimal places as a whole number, and the BigInt additions are exact. The only rounding happens once, at the end.

Step 5: score the methods

Step 5

console.log(naive(harmonic) - reference);         // -9.237055564881302e-14
console.log(kahan(harmonic) === reference);        // true
console.log(pairwise(harmonic) === reference);     // true
const ascending = harmonic.slice().reverse();
console.log(naive(ascending) - reference);        // -1.9539925233402755e-14

The plain sum is out by about 9 in the 14th decimal place. Kahan and pairwise both match the reference exactly. Simply adding the smallest terms first cuts the plain sum's error by about 4.7 times, because small numbers get to add up together before they meet a big total.

Step 6: the list that breaks Kahan

Step 6

const hostile = [1, 1e100, 1, -1e100];
console.log(naive(hostile), kahan(hostile)); // 0 0

The true answer is 2. Kahan's correction t - sum - y assumes the running total is the bigger number. When the next term is 1e100, that is backwards, and the lost 1 is never recovered.

Step 7: Neumaier's fix

Step 7

function neumaier(xs) {
  let sum = 0;
  let c = 0;
  for (const x of xs) {
    const t = sum + x;
    c += Math.abs(sum) >= Math.abs(x) ? sum - t + x : x - t + sum;
    sum = t;
  }
  return sum + c;
}
console.log(neumaier(hostile), neumaier([1e16, 3, -1e16])); // 2 3

Neumaier checks which of the two numbers is bigger and works out the loss from the right end. It also saves all the losses in c and adds them back once at the end. Both lists now come out right. On [1e16, 3, -1e16], the plain sum, Kahan and pairwise all say 4.

Step 8: what no sum can fix

Step 8

console.log(kahan([0.1, 0.2]), neumaier([0.1, 0.2])); // 0.30000000000000004 0.30000000000000004

This is one addition, correctly rounded, of two numbers that were already slightly off. Nothing was dropped along the way, so there is nothing to recover. If you need exact decimals, like money, count in whole numbers instead.

The full solution

The answer panel has all four methods and the BigInt reference, and prints each case above. Press Run to see the output.

The answer

const naive = (xs) => xs.reduce((a, b) => a + b, 0);

// Kahan: `c` carries what the last addition lost, and is removed from the next term.
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;
}

// Neumaier: works out which operand was larger, accumulates the loss instead of
// folding it into the next term, and adds it back at the very end.
function neumaier(xs) {
  let sum = 0;
  let c = 0;
  for (const x of xs) {
    const t = sum + x;
    c += Math.abs(sum) >= Math.abs(x) ? sum - t + x : x - t + sum;
    sum = t;
  }
  return sum + c;
}

// Pairwise: halve, sum each half, add. No compensation, no extra state.
function pairwise(xs, lo, hi) {
  const from = lo === undefined ? 0 : lo;
  const to = hi === undefined ? xs.length : hi;
  if (to - from <= 8) {
    let s = 0;
    for (let i = from; i < to; i++) s += xs[i];
    return s;
  }
  const mid = (from + to) >> 1;
  return pairwise(xs, from, mid) + pairwise(xs, mid, to);
}

const N = 100000;
const tenths = new Array(N).fill(0.1);
const harmonic = Array.from({ length: N }, (_, i) => 1 / (i + 1));

// A reference for the harmonic sum, in exact integers: 30 decimal places of
// each term, added as BigInt, so the only error is the final conversion.
const SCALE = 10n ** 30n;
let scaled = 0n;
for (let k = 1n; k <= BigInt(N); k++) scaled += SCALE / k;
const reference = Number(scaled) / 1e30;

const ascending = harmonic.slice().reverse();          // smallest term first
const hostile = [1, 1e100, 1, -1e100];                 // true sum: 2
const cancelling = [1e16, 3, -1e16];                   // true sum: 3

console.log('100000 tenths, naive :', naive(tenths));
console.log('kahan / neumaier     :', kahan(tenths), neumaier(tenths));
console.log('pairwise             :', pairwise(tenths));
console.log('harmonic reference   :', reference);
console.log('naive, descending    :', naive(harmonic), naive(harmonic) - reference);
console.log('naive, ascending     :', naive(ascending), naive(ascending) - reference);
console.log('kahan / pairwise     :', kahan(harmonic), pairwise(harmonic));
console.log('hostile list         :', naive(hostile), kahan(hostile), neumaier(hostile), '<- want 2');
console.log('cancelling list      :', naive(cancelling), kahan(cancelling), neumaier(cancelling), '<- want 3');
console.log('a single addition    :', kahan([0.1, 0.2]), neumaier([0.1, 0.2]));

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('adding 100000 tenths straight through overshoots 10000', [naive(tenths), naive(tenths) === 10000], [10000.000000018848, false]);
test('Kahan, Neumaier and pairwise all land on 10000 exactly', [kahan(tenths), neumaier(tenths), pairwise(tenths)], [10000, 10000, 10000]);
test('the integer reference for the harmonic sum is 12.090146129863427', reference, 12.090146129863427);
test('Kahan and pairwise both hit that reference bit for bit', [kahan(harmonic) === reference, pairwise(harmonic) === reference], [true, true]);
test('where the naive sum is out by 9.2e-14 after 100000 terms', naive(harmonic) - reference, -9.237055564881302e-14);
test('sorting the terms smallest first cuts that error by a factor of 4.7, with no compensation', naive(ascending) - reference, -1.9539925233402755e-14);
test('but on this list Kahan is as wrong as the naive sum, and Neumaier is right', [naive(hostile), kahan(hostile), neumaier(hostile)], [0, 0, 2]);
test('and here all three of naive, Kahan and pairwise say 4 where the answer is 3', [naive(cancelling), kahan(cancelling), pairwise(cancelling), neumaier(cancelling)], [4, 4, 4, 3]);
test('neither compensation turns 0.1 + 0.2 into 0.3, because that error is not accumulation', [kahan([0.1, 0.2]), neumaier([0.1, 0.2])], [0.30000000000000004, 0.30000000000000004]);

Exercise 14 introduced Kahan summation as the fix for an accumulating error. This is the version with the fine print. Over 100000 tenths, and over 100000 harmonic terms checked against a BigInt reference computed to thirty decimal places, compensation earns its keep: Kahan and pairwise both land on the reference bit for bit, where the straight sum is out by 9.2e-14. Pairwise deserves attention — it is three lines, keeps no correction term, and matched the exact answer here, because splitting the list halves the depth of the addition chain and the error grows like log n instead of n.

Then [1, 1e100, 1, -1e100]. The true sum is 2. Kahan returns 0, exactly like the naive sum, because its correction is computed as t - sum - y on the assumption that sum is the larger operand — and when the incoming term is 1e100 times bigger, that subtraction recovers nothing. Neumaier's variant tests which operand is larger, accumulates the loss separately, and adds it back at the end, so it returns 2. [1e16, 3, -1e16] is the same shape in miniature: naive, Kahan and pairwise all say 4, Neumaier says 3.

And the last assertion is the boundary of the whole technique. Compensated summation fixes error that accumulates across additions. It cannot fix an operand that was already wrong: 0.1 + 0.2 is a single correctly rounded addition of two inexact doubles, there is nothing dropped to recover, and every method here returns 0.30000000000000004. If you need decimal exactness, scale to integers — the previous exercise — rather than reaching for a cleverer sum.

Common mistakes

  • Assuming Kahan is always right. A term much bigger than the running total defeats it. Neumaier's version handles that case.
  • Expecting compensation to fix 0.1 + 0.2. It only fixes error that builds up across many additions.
  • Testing a sum against a value you guessed. Build an exact reference, here with BigInt, so you know what right looks like.

Try it yourself

  1. Add a million copies of 0.01 with each method. Which ones give exactly 10000?
  2. Sort hostile by size before adding it naively. Does that help?
  3. Change pairwise to stop splitting at 2 items instead of 8, and compare the results on harmonic.

Keep practising

Newsletter

New writing, when it lands.

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