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.
Code
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.5How 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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.