Sub topic 4
Floating-point surprises: isclose and fsum
This chapter assumes you know Python numbers and if statements, and that you can import a module as shown in the earlier chapters. It covers why float arithmetic gives odd results, how to compare floats safely, and how to add many floats accurately.
Why 0.1 + 0.2 is not 0.3
A float is stored in binary. Many decimal fractions, such as 0.1, have no exact binary form, just as 1/3 has no exact decimal form. Python stores the nearest value it can, and small errors appear in the results.
import math
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 broken here. Any language that uses standard double-precision floats shows the same behavior.
Comparing with math.isclose
Use math.isclose(a, b) instead of == when either value may carry rounding error. It returns True when the two values differ by less than a tolerance.
It has two tolerance settings:
| Parameter | Default | Meaning |
|---|---|---|
| `rel_tol` | `1e-09` | Allowed difference relative to the larger of the two values |
| `abs_tol` | `0.0` | Allowed difference in absolute terms |
The relative tolerance scales with the numbers, so it works for both 3.0 and 3,000,000.0. It fails near zero, because a relative gap to zero is always 100 percent. You must set abs_tol when you compare against 0.
import math
print(math.isclose(1e-12, 0.0)) # False
print(math.isclose(1e-12, 0.0, abs_tol=1e-9)) # True
print(math.isclose(100.0, 100.00001, rel_tol=1e-6)) # TrueAdding many floats with fsum
Each addition in sum() rounds its result, and the errors accumulate. math.fsum() tracks the lost low-order bits and rounds only once at the end.
import math
print(sum([0.1] * 10)) # 0.9999999999999999
print(math.fsum([0.1] * 10)) # 1.0
print(sum([1e100, 1.0, -1e100])) # 0.0
print(math.fsum([1e100, 1.0, -1e100])) # 1.0In the second example, the 1.0 is lost completely when it is added to 1e100, so sum() returns 0.0. fsum() keeps it.
fsum is slower than sum, so use it when accuracy matters more than speed, for example when you add thousands of measurements. It also accepts any iterable of numbers, not only lists.
Choosing the right tool
Common mistakes
- Using
==or!=on computed floats. Usemath.isclose. - Forgetting
abs_tolwhen you compare with zero. - Choosing a tolerance that is too loose, which hides real differences. Pick
rel_tolfrom the precision your data actually has. - Assuming
fsumfixes the stored error of each input. It does not.0.1is still the nearest float to 0.1.fsumonly avoids adding extra error during the sum. - Using floats for currency. Cents such as 0.10 cannot be stored exactly. Store integer cents or use the
decimalmodule.
Integers are always exact in Python, so the problems in this chapter apply only to floats.
Exercise
A function computes total = sum([0.1, 0.2, 0.3]) and then checks if total == 0.6. The check fails. Rewrite the code so the check passes reliably, and explain why math.isclose(total - 0.6, 0.0) would still be a poor fix.
Show answer
Use import math, then total = math.fsum([0.1, 0.2, 0.3]) and if math.isclose(total, 0.6):. The isclose call is the part that makes the check reliable, because sum gives 0.6000000000000001 and == cannot tolerate that gap. Writing math.isclose(total - 0.6, 0.0) is a poor fix because the default abs_tol is 0.0, so comparing against zero with only a relative tolerance returns False for any nonzero difference. You would need to pass abs_tol as well, and comparing total with 0.6 directly is simpler.