Skip to content
Use Python fsum when floating-point totals cancel

Use Python fsum when floating-point totals cancel

November 22, 2026

A running floating-point total can discard a small adjustment when much larger positive and negative values cancel. Keep the original observations available and compare the accumulation methods before trusting a reconciliation total.

Run the example

Tested on Linux with Python 3.12.14. No third-party packages are required. In one Bash session, create a disposable directory:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Save this as demo_python_fsum_cancellation_totals.py. Use that filename to avoid shadowing a standard-library module.

from math import fsum

adjustments = [1e16, 1.0, -1e16]
running = 0.0
for value in adjustments:
    running += value

print("running total:", running)
print("fsum total:", fsum(adjustments))
print("reordered fsum:", fsum(reversed(adjustments)))
print("decimal-input residual:", fsum([0.1, 0.2, -0.3]))

Run it:

python3 demo_python_fsum_cancellation_totals.py

Output:

running total: 0.0
fsum total: 1.0
reordered fsum: 1.0
decimal-input residual: 2.7755575615628914e-17

The explicit running loop loses the unit adjustment before subtracting the large value. fsum retains intermediate partial sums and recovers it in this example. The final line shows a different problem: the inputs already approximate decimal fractions, so accurate accumulation does not make their decimal relationship exact.

Input policy and limits

Use decimal arithmetic with an explicit rounding policy for decimal accounting. Keep nonfinite values out of ordinary measurement totals and decide how to handle overflow. This example does not claim that every summation algorithm or Python version has the same behavior as the explicit loop; built-in sum has changed across versions. The documented platform rounding caveats for fsum still apply.

Clean up

In the same Bash session, remove the source file and the empty working directory:

rm -- demo_python_fsum_cancellation_totals.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its contents before deleting anything else.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on