ML Foundations
Check cancellation in a Python floating-point sum
Compare sequential accumulation with math.fsum on a small reproducible cancellation example.

Evidence and testing
Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.
Small terms can disappear during accumulation
When numbers with very different magnitudes are accumulated in a floating-point loop, a small term can be rounded away before large positive and negative values cancel. The order of operations then matters. This can affect an aggregate of mixed-scale contributions even when each individual value appears reasonable. [2]
Python provides math.fsum to track multiple intermediate partial sums and improve accuracy. It still returns a floating-point result; it is not a promise of exact arithmetic in every case. [1]
Run a concrete cancellation check
Run python examples/python_fsum_cancellation.py. In this fixture, sequentially adding one to 1e16 rounds away that small contribution. Subtracting 1e16 then leaves zero. math.fsum instead returns one for the same three input floats, matching their exact mathematical sum. [1, 2]
The assertions verify both outputs, and the example uses an explicit loop so the order of the additions is visible. This avoids assuming that the built-in sum uses the same algorithm across Python versions.
This is an illustrative example, not a claim that every dataset produces this discrepancy or that math.fsum is always faster.
Executed with Python 3.12.14; stdout and checksum are in private evidence.
import math
values = [1e16, 1.0, -1e16]
total = 0.0
for value in values:
total += value
accurate = math.fsum(values)
assert total == 0.0
assert accurate == 1.0
print("sequential:", total)
print("fsum:", accurate)
print("small term preserved:", accurate == 1.0)
Recorded output
sequential: 0.0 fsum: 1.0 small term preserved: True
Use the right error contract
For a real reduction, consider the data range, the size and order of terms, and the precision required by downstream decisions. Compare a representative fixture to a suitably precise reference instead of relying only on printed decimal places. [2]
This example covers finite scalar floats. Nonfinite values, overflow, parallel reductions and exact-decimal requirements need separate handling. The result does not establish an error bound or a performance measurement for a production pipeline. [1]