Sub topic 4
Floating-point precision and math.isclose
This chapter assumes you can run Python scripts, know int and float, and have read the chapter on comparison operators. Here you will learn why == on floats sometimes fails, how large the error is, and how to compare floats correctly.
Why 0.1 + 0.2 is not 0.3
Python's float is an IEEE 754 double-precision binary number. It stores 53 significant bits. Many decimal fractions, such as 0.1, have no finite binary expansion, just as 1/3 has no finite decimal expansion. Python stores the nearest representable value instead.
from decimal import Decimal
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(f"{0.1:.20f}")
print(Decimal(0.1))The output is:
0.30000000000000004
False
0.10000000000000000555
0.1000000000000000055511151231257827021181583404541015625Decimal(0.1) shows the exact value the float holds. It is slightly more than 0.1. Adding 0.1 and 0.2 combines two rounded values, and the rounded result lands one step away from the double nearest to 0.3.
This is not a Python bug. Any language that uses hardware doubles behaves the same way. Python's repr prints the shortest string that round-trips to the same float. That is why 0.1 displays as 0.1 even though the stored value is not exactly 0.1.
What is exact and what is not
Not every float operation loses precision. The following are exact:
- Integers up to 2**53 (9,007,199,254,740,992) stored as floats.
- Fractions whose denominator is a power of two, such as 0.5, 0.25 and 0.125.
- Multiplication or division by a power of two (barring overflow or underflow).
Beyond 2**53, floats skip integers.
big = 2.0 ** 53
print(big + 1 == big)
print(0.5 + 0.25 == 0.75)
print(sum([0.1] * 10))
print(sum([0.1] * 10) == 1.0)The output is True, True, 0.9999999999999999 and False. Each addition rounds, and the errors accumulate. The more operations you chain, the further the result can drift from the mathematical answer.
Comparing with math.isclose
Instead of testing exact equality, test whether two values are close. The standard library provides math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0). It returns True when:
abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)import math
print(math.isclose(0.1 + 0.2, 0.3))
print(math.isclose(100, 101, rel_tol=0.02))
print(math.isclose(0.1 + 0.2, 0.3, rel_tol=1e-12))All three print True. The default rel_tol of 1e-09 allows about nine matching decimal digits. A double carries roughly 15 to 17 significant digits, so the default tolerates a few accumulated rounding errors without hiding real differences.
Relative versus absolute tolerance
A relative tolerance scales with the size of the numbers. A gap of 1 is large between 3 and 4 but tiny between 1e12 and 1e12 + 1. The relative tolerance in isclose uses the larger of the two magnitudes, so the test is symmetric: isclose(a, b) always equals isclose(b, a).
The problem appears near zero. Any relative tolerance of a number times zero is zero, so a nonzero value is never "close" to 0.0 under a purely relative test.
import math
print(math.isclose(1e-10, 0.0))
print(math.isclose(1e-10, 0.0, abs_tol=1e-9))
print(math.isclose(0.1 + 0.2 - 0.3, 0.0))
print(math.isclose(0.1 + 0.2 - 0.3, 0.0, abs_tol=1e-12))This prints False, True, False, True. When either value might be zero, such as the result of a subtraction, set abs_tol to the smallest difference that matters for your problem.
Special values
math.isclose(math.inf, math.inf)isTrue. Infinities are close only to an infinity of the same sign.math.isclose(math.nan, math.nan)isFalse, consistent withnan == nanbeingFalse.- Negative tolerances raise
ValueError.
Choosing a comparison strategy
| Tool | Exact for 0.1 + 0.2 == 0.3? | Cost | Typical use |
|---|---|---|---|
| `float` with `==` | No | Fastest | Only when values are exactly representable |
| `float` with `math.isclose` | Close enough | Fast | Measurements, simulations, tests |
| `decimal.Decimal` | Yes, if built from strings | Slower | Money, decimal rules |
| `fractions.Fraction` | Yes | Slower, size grows | Exact rational arithmetic |
| Integers (cents) | Yes | Fast | Currency in the smallest unit |
from decimal import Decimal
from fractions import Fraction
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
print(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10))
print(Decimal(0.1) + Decimal(0.2) == Decimal("0.3"))The output is True, True, False. The last line fails because Decimal(0.1) copies the already-rounded float. Build a Decimal from a string, not from a float.
Common errors
- Using
==on computed floats. Any result of division,sqrt, or repeated addition is suspect. Usemath.isclose. - Forgetting
abs_tolnear zero. A check likeisclose(error, 0.0)is almost alwaysFalse. - Loops that rely on exact stepping.
while x != 1.0: x += 0.1never terminates. Use<or an integer counter. - Trusting
round.round(2.675, 2)returns2.67, because the stored value is slightly below 2.675. UseDecimalwith an explicit rounding mode when decimal rounding rules matter. - Summing many floats naively. Use
math.fsum, which tracks lost low-order bits. - Using one tolerance everywhere. A tolerance is a statement about your data. Pick it from the accuracy you need, not from habit.
import math
values = [0.1] * 10
print(sum(values) == 1.0)
print(math.fsum(values) == 1.0)This prints False and then True.
<br>
Exercises
Exercise
What does math.isclose(1e-12, 0.0) return, and what change makes it return True?
Show answer
It returns False, because the default abs_tol is 0.0 and a relative tolerance multiplied by a number near zero is nearly zero. Pass an absolute tolerance at least as large as the difference, for example math.isclose(1e-12, 0.0, abs_tol=1e-9).
Exercise
Why does Decimal(0.1) + Decimal(0.2) == Decimal("0.3") evaluate to False, and how do you fix it?
Show answer
Decimal(0.1) converts the binary float, which already holds a rounded value slightly above 0.1, so the sum is not exactly 0.3. Build the values from strings: Decimal("0.1") + Decimal("0.2") == Decimal("0.3") is True.
Exercise
Write a function total_matches(prices, expected) that returns True when the sum of a list of float prices equals expected to within a relative tolerance of 1e-9, and sums accurately.
Show answer
import math def totalmatches(prices, expected): return math.isclose(math.fsum(prices), expected, reltol=1e-9) print(total_matches([0.1] * 10, 1.0))