Sub topic 4
Floating-point precision and math.isclose
This chapter assumes you can run Python code, know the built-in int, float, and bool types, and have used == and arithmetic operators. By the end you will know why some float comparisons fail and how to compare floats safely.
Why 0.1 + 0.2 is not 0.3
A Python float is stored in binary, as a fraction whose denominator is a power of two. Some decimal numbers, such as 0.5 and 0.25, fit exactly. Others, such as 0.1 and 0.2, repeat forever in binary. Python stores the nearest value it can, so a tiny error is already present before any arithmetic happens.
When you add two such values, the errors combine:
import math
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))The first line prints False. The second prints True. Printing 0.1 + 0.2 shows 0.30000000000000004, which is a different float from 0.3.
This is not a Python bug. Languages that use IEEE 754 double-precision floats behave the same way.
Comparing with math.isclose
math.isclose(a, b) returns True when a and b are close enough. It uses two tolerances:
rel_tolis a relative tolerance. The default is1e-09, which is about nine matching decimal digits.abs_tolis an absolute tolerance. The default is0.0.
The test passes when the difference is at most rel_tol times the larger of the two magnitudes, or at most abs_tol.
Comparing against zero
The relative tolerance breaks down near zero, because any relative fraction of zero is zero. With the default abs_tol=0.0, nothing except zero itself is close to zero:
import math
tiny = 1e-12
print(math.isclose(tiny, 0.0))
print(math.isclose(tiny, 0.0, abs_tol=1e-9))The first call prints False. The second prints True. Set abs_tol whenever one of the values might be zero or very small.
Common errors
- Using
==on the result of float arithmetic. Usemath.iscloseinstead. - Using one tolerance for every problem. Pick
rel_tolandabs_tolto match the precision your data really has. - Using floats for money. When you need exact decimal arithmetic, use the
decimalmodule. - Using
isclosefor ordering checks. For<or>, plain comparison is usually fine.
Exercise
What do math.isclose(1e-12, 0.0) and math.isclose(1e-12, 0.0, abs_tol=1e-9) print, and why do they differ?
Show answer
The first prints False and the second prints True. The default abstol is 0.0, and the relative tolerance is scaled by the larger magnitude, so it allows only a tiny difference from 1e-12. That does not cover the gap between 1e-12 and 0.0. Setting abstol=1e-9 allows an absolute difference up to 1e-9, which covers 1e-12.
Exercise
Rewrite if total == 0.3: so it is safe when total is the sum of 0.1 and 0.2.
Show answer
Use if math.isclose(total, 0.3): after import math.