Use math.fsum for a more accurate float total
Also published in our Blogger archive.
Adding floating-point values strictly from left to right can lose a small value when it sits between much larger values. math.fsum() is a standard-library summation function that keeps intermediate partial sums to improve accuracy for floating-point inputs.
The list in this example contains a large positive value, 1.0, and an equally large negative value. The explicit loop models left-to-right accumulation: adding 1.0 to 1e16 rounds back to 1e16, so the later negative value leaves 0.0. math.fsum() retains the small contribution for this input and returns 1.0. The assertions check these two specific results, while the printed lines make the contrast deterministic.
This exact example requires Python 3.6+ because its output statements use formatted string literals (f-strings); math.fsum() itself is available in Python 3. Do not assume that built-in sum() always behaves like the explicit loop: its floating-point summation implementation has improved in recent Python versions. fsum() also does not make every numerical result exact. It returns a float, whose finite precision and special values still matter, and the documentation notes a possible least-significant-bit difference on some non-Windows builds using extended-precision intermediate addition. For currency stored in minor units, integer arithmetic is often clearer; for specified decimal rounding rules, consider decimal.Decimal.
The official math.fsum reference documents its partial-sums approach and platform rounding caveat. The f-strings documentation records that formatted string literals were added in Python 3.6.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed for the target numerical domain.
import math
adjustments = [1e16, 1.0, -1e16]
left_to_right = 0.0
for adjustment in adjustments:
left_to_right += adjustment
accurate_total = math.fsum(adjustments)
assert left_to_right == 0.0
assert accurate_total == 1.0
print(f"left-to-right: {left_to_right}")
print(f"fsum: {accurate_total}")
left-to-right: 0.0
fsum: 1.0