Numerical analysis
Floating-point arithmetic
Error reduction
Computational methods
Summation algorithm

Kahan summation algorithm

Codemia Knowledge Hub ·

Kahan summation is a compensated summation algorithm that reduces floating-point rounding error when adding many values. It keeps a second variable that captures the low-order bits lost in each addition and feeds them back into the next one. It does not make floating-point arithmetic exact, but it is often noticeably more accurate than naive left-to-right accumulation at very low extra cost.

Why ordinary summation loses accuracy

Floating-point numbers have limited precision. When you add a tiny number to a much larger one, the tiny contribution can disappear during rounding. A classic example:

python
values = [1e16, 1.0, -1e16]
print(sum(values))

Mathematically the result is 1.0, but naive left-to-right floating-point accumulation produces 0.0. This is a property of finite-precision floating point, not of any one language. (On Python 3.12 and later, the built-in sum() already uses Neumaier's compensated summation for floats, so this particular line prints 1.0. A plain for loop with += still shows the loss.)

How the algorithm works

Kahan summation keeps a compensation term that remembers the low-order bits lost in previous additions. At each step:

  1. subtract the compensation from the new value
  2. add the corrected value to the running sum
  3. compute the new rounding error
  4. store that error as the next compensation

This lets the algorithm re-inject information that naive summation would lose permanently.

Python implementation

python
1def kahan_sum(values):
2    total = 0.0
3    c = 0.0
4
5    for x in values:
6        y = x - c
7        t = total + y
8        c = (t - total) - y
9        total = t
10
11    return total
12
13
14def naive_sum(values):
15    total = 0.0
16    for x in values:
17        total += x
18    return total
19
20
21values = [1e16, 1.0, -1e16]
22print("naive :", naive_sum(values))
23print("kahan :", kahan_sum(values))

Be careful with this particular input: classic Kahan returns 0.0 for [1e16, 1.0, -1e16], because the lost 1.0 is held in the compensation term and then rounded away again when it is combined with the much larger -1e16. Inputs where a later term is larger than the running sum are exactly the case that Neumaier's variant (the one behind Python 3.12's sum()) fixes. Kahan's strength is the long run of small additions shown further down.

What the compensation variable holds

The compensation term is not the exact mathematical error. It is the rounding loss from the previous addition, captured so the next step can use it. That is why this update looks odd at first:

python
c = (t - total) - y

It reconstructs the low-order bits that rounding swallowed when y was added to total. Without it, those bits would vanish.

Many small values against a large one

python
1values = [1e8] + [1e-5] * 1_000_000 + [-1e8]
2
3print("naive :", naive_sum(values))  # naive : 9.998679161071777
4print("kahan :", kahan_sum(values))  # kahan : 10.0

The exact result is about 10.0. Naive left-to-right summation can drift noticeably, while Kahan tracks the small contributions much better. This is the scenario where compensated summation earns its keep.

When Kahan helps most

Kahan summation is most useful when:

  • summing a long list of values
  • magnitudes vary widely
  • cancellation happens often
  • small errors accumulate into visible drift

Typical areas include statistics, simulation, finance, physics and iterative numerical methods. If the list is short and the numbers are similar in magnitude, the improvement may be small. Check whether your workload actually has a numerical stability problem, and do not generalize from one toy example.

What Kahan does not guarantee

  • it does not make floating point exact
  • it does not beat every advanced summation method in every case
  • it still depends on data order

Stronger techniques exist, such as pairwise summation and more advanced compensated schemes, but Kahan is a good middle ground because it is simple and cheap.

Performance cost

Kahan adds a few arithmetic operations per element. For most business and scientific workloads that overhead is modest compared with the accuracy gained.

If you sum massive arrays inside tight numeric kernels, benchmark before replacing optimized array-library reductions, because:

  • vectorized library routines may already use other stable techniques
  • the memory access pattern may dominate
  • hardware and compiler behavior can matter

Apply it deliberately where numerical error matters enough to justify a small extra cost per addition, not as a default for every sum.


Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms