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.

PythonData Integrity

Code

pythonsnippet
30 lines
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.0

What 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

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:`.