Sub topic 4
Floating-point surprises: isclose and fsum
This chapter assumes you can write Python functions and loops and that you have met the math module's constants and functions. It covers why float arithmetic gives results like 0.30000000000000004, how to compare floats with math.isclose, and how to add them accurately with math.fsum.
Why 0.1 + 0.2 is not 0.3
Python's float follows the IEEE 754 double-precision standard. A float stores a number as a binary fraction with 53 significant bits. Many decimal fractions, including 0.1, have no exact binary form. The same thing happens in base 10 with 1/3, which becomes 0.3333... and has to be cut off somewhere.
Printing more digits shows what is actually stored:
import math
print(format(0.1, ".20f")) # 0.10000000000000000555
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # TruePython is not making a mistake here. Each of 0.1, 0.2 and 0.3 is the nearest representable double to the decimal you typed. Adding the first two gives a double that is one step away from the double nearest to 0.3. == compares exact bit patterns, so it reports False.
Two rules follow:
- A float is an approximation. Small errors, about one part in 10^16, are normal.
- Errors can grow when you do many operations, or when you subtract two nearly equal numbers.
Comparing floats with math.isclose
math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) returns True when the two values are close enough. Internally it tests:
abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)The check is symmetric, so isclose(a, b) always equals isclose(b, a). The relative tolerance scales with the larger of the two values. The absolute tolerance is a fixed floor.
import math
print(math.isclose(1e10, 1e10 + 1)) # True: difference 1 is below 1e10 * 1e-9 = 10
print(math.isclose(1.0, 1.0000001)) # False: relative difference is about 1e-7
print(math.isclose(0.0, 1e-12)) # False
print(math.isclose(0.0, 1e-12, abs_tol=1e-9)) # True
print(math.isclose(math.inf, math.inf)) # True
print(math.isclose(math.nan, math.nan)) # FalseThe same absolute difference can be large or tiny depending on the magnitudes. A difference of 1 is negligible between two numbers near ten billion and enormous between two numbers near 1.0. A relative tolerance handles this automatically.
The zero problem
A relative tolerance is a fraction of the numbers being compared. When one of them is exactly 0.0, that fraction is 0.0, so nothing except an exact match passes. This is why isclose(0.0, 1e-12) is False by default.
Whenever zero is a plausible expected value, set abs_tol to the smallest difference that matters in your problem. A value of 1e-9 is a reasonable starting point for quantities of order 1. It is too large for values around 1e-12, and too small if your inputs carry measurement noise.
Choosing tolerances
The default rel_tol=1e-09 means "equal to about nine decimal digits". That suits results computed in double precision with a handful of operations.
- Loosen it (for example
rel_tol=1e-6) when the data comes from sensors, files with rounded values, or long calculations. - Tighten it only if you know the computation is very well conditioned.
rel_tolvalues below about1e-15can reject numbers that differ by a single rounding step. rel_tolmust not be negative, and neither tolerance may be negative. Python raisesValueErrorotherwise.nanis never close to anything, including itself.infis close only to the same infinity.
Where float equality bites in practice
Exact == on floats causes trouble in several places:
- A loop such as
while x != 1.0that adds 0.1 each time may never stop. - A test like
assert result == 0.3fails depending on the order of operations. - Float keys in a
dictorsettreat0.30000000000000004and0.3as different keys. if x <= limitcan fail by one rounding step at the boundary. Decide whether the boundary case matters, and if it does, combineisclosewith the ordering test.
In tests, math.isclose works well inside assert. If you use pytest, pytest.approx does the same job.
import math
def average(values):
return math.fsum(values) / len(values)
assert math.isclose(average([0.1, 0.2, 0.3]), 0.2)
print("ok")Adding floats accurately with math.fsum
Each + on floats rounds its result. When you add many numbers in a loop, those rounding errors accumulate. math.fsum(iterable) avoids this. It keeps exact partial sums internally and rounds only once, at the end. The result is the correctly rounded sum of the values you passed in.
import math
def running_total(values):
total = 0.0
for v in values:
total += v
return total
print(running_total([0.1] * 10)) # 0.9999999999999999
print(math.fsum([0.1] * 10)) # 1.0
tricky = [1e100, 1.0, -1e100, 1.0]
print(running_total(tricky)) # 1.0
print(math.fsum(tricky)) # 2.0In the second example, the plain loop loses the first 1.0 entirely. It is smaller than one rounding step at 1e100, so adding it changes nothing. Then the big values cancel and only the last 1.0 survives. fsum tracks the lost pieces and recovers the right answer, 2.0.
What about the built-in sum?
The built-in sum is faster and works on any type that supports +, but it behaves differently depending on the Python version:
- Before Python 3.12,
sumof floats adds left to right with ordinary rounding.sum([0.1] * 10)gives0.9999999999999999. - From Python 3.12,
sumuses a compensated algorithm for floats. It is much more accurate, andsum([0.1] * 10)can give1.0. It is still not guaranteed to be correctly rounded in every case.
If your result must not depend on the interpreter version, use math.fsum.
| Tool | Accepts | Accuracy | Speed |
|---|---|---|---|
| `+=` in a loop | any numbers | error grows with length | fast |
| `sum()` | any addable type | version dependent for floats | fast |
| `math.fsum()` | ints and floats | correctly rounded result | slower |
Limits of fsum
fsumfixes the error from adding. It does not fix error already present in the inputs. If a value was computed as0.1 + 0.2, it carries that error into the sum.- It returns a
float. If you pass integers, you still get a float, which can lose precision for ints above 2^53. Use plainsumfor integers. - It does not accept
DecimalorFraction. Usesumfor those. - A very long iterable costs more time than
sum, but memory use stays small. The partial sums are bounded. - If the inputs include infinities of opposite sign, or
nan, the result isnan. Overflow in the final sum raisesOverflowError.
When floats are the wrong tool
For money, or any value that must be exact in decimal, avoid binary floats altogether. The decimal module stores decimal digits exactly, and fractions.Fraction stores exact ratios. Both cost more time than floats.
from decimal import Decimal
from fractions import Fraction
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3")) # True
print(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10)) # True
print(Decimal(0.1))
# 0.1000000000000000055511151231257827021181583404541015625Notice the last line. Decimal(0.1) starts from the already inexact float. Build a Decimal from a string, Decimal("0.1"), to get exactly the digits you typed.
A rough decision guide:
- Scientific or statistical work with measured data: use floats,
iscloseandfsum. - Currency, invoices, tax: use
Decimalwith strings, and compare with==. - Exact rational arithmetic: use
Fraction. - Counting: use
int.
Common mistakes
- Using
==on computed floats. Usemath.isclose. - Using
iscloseagainst0.0with noabs_tol. It will almost always returnFalse. - Setting
abs_tolto something huge to "make the test pass". This hides real errors. - Assuming
sumandfsumagree. They can differ in the last digits. - Building
Decimalfrom a float instead of a string. - Trying to "fix" the display with
round. Rounding changes how a value prints, but the stored value still carries its error. Compare withiscloseinstead.
Exercise
A function computes a voltage drop and returns 4.4e-16 when the true answer is 0. The test says assert math.isclose(result, 0.0), and it fails. Why does it fail, and what is the smallest fix?
Show answer
With abs_tol=0.0, the allowed difference is rel_tol * max(abs(a), abs(b)), which is about 1e-09 * 4.4e-16, far smaller than 4.4e-16. Only an exact zero would pass. Add an absolute tolerance that matches the scale of your problem, for example math.isclose(result, 0.0, abs_tol=1e-12).
Exercise
What do running_total([1e100, 1.0, -1e100, 1.0]) and math.fsum([1e100, 1.0, -1e100, 1.0]) return, using the running_total function from this chapter, and why do they differ?
Show answer
The loop returns 1.0 and fsum returns 2.0. In the loop, adding 1.0 to 1e100 is lost to rounding, so only the final 1.0 survives after the large values cancel. fsum keeps exact partial sums and rounds once at the end, so both 1.0 values are counted.