math.fsum Tracks Every Intermediate Bit

math.fsum tracks every intermediate bit so the total matches exact decimal intent, while builtin sum accumulates binary float error on repeated additions.

PythonData Integrity

Code

pythonsnippet
16 lines
import math

values = [0.1] * 10

# 内建 sum 累积二进制浮点误差:结果差一点点
print('sum  :', repr(sum(values)))
# fsum 跟踪全部中间位,返回精确和
print('fsum :', repr(math.fsum(values)))
print('equal:', sum(values) == math.fsum(values))

# 大小悬殊的列表更明显:小项被大项吞掉
mixed = [1e16, 1.0, -1e16]
print('swallowed:', sum(mixed), math.fsum(mixed))

# fsum 也接受生成器:一次遍历,不建列表
print('gen  :', math.fsum(x / 10 for x in range(10)))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

sum  : 0.9999999999999999
fsum : 1.0
equal: False
swallowed: 0.0 1.0
gen  : 4.5

How the snippet works

Module-level bindings hold the data — values, mixed — with no function scope in between.

Using it

The demo output is labeled (sum :, fsum :, equal:), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `math`. Its state lives in module-level bindings: `values`, `mixed`.