Compensated Summation with Kahan
Reduce floating-point drift with Kahan and Neumaier compensated summation, and see where plain left-to-right addition loses a value.
Code
def kahan_sum(values: list[float]) -> float:
total = 0.0
compensation = 0.0
for value in values:
adjusted = value - compensation
updated = total + adjusted
compensation = (updated - total) - adjusted
total = updated
return total
def neumaier_sum(values: list[float]) -> float:
total = 0.0
compensation = 0.0
for value in values:
updated = total + value
if abs(total) >= abs(value):
compensation += (total - updated) + value
else:
compensation += (value - updated) + total
total = updated
return total + compensation
if __name__ == "__main__":
values = [1e16, 1.0, -1e16, 1.0]
print("naive:", sum(values))
print("kahan:", kahan_sum(values))
print("neumaier:", neumaier_sum(values))
Output
Captured from a sandboxed run of this snippet in the build pipeline.
naive: 1.0
kahan: 1.0
neumaier: 2.0What the code does
The part worth importing is the functions kahan_sum and neumaier_sum — everything else is wiring.
Repetition is confined to for value in values — the rest of the file is straight-line.
Applying it
The signature you will reach for first is def kahan_sum(values: list[float]) -> float
The demo output is labeled (naive:, kahan:, neumaier:), so the printed output reads as a trace of the operations performed.
Statements that matter
def kahan_sum(values: list[float]) -> float:
total = 0.0
compensation = 0.0
for value in values:
adjusted = value - compensation
updated = total + adjusted
compensation = (updated - total) - adjusted
total = updated
return total
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- What does Compensated Summation with Kahan print when run?
- Running the file directly is enough — expect labeled output lines such as `naive:`, `kahan:`, `neumaier:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.