Sub topic 8
Floating-point precision, math.isclose, and Decimal
This chapter assumes you can run Python code, use print(), and already know the int and float types and the arithmetic operators from earlier chapters. Here you will see why 0.1 + 0.2 != 0.3, how to compare floats safely, and when to use Decimal instead.
Why 0.1 + 0.2 is not 0.3
A Python float is a 64-bit IEEE 754 binary floating-point number. It stores a sign, an exponent, and 53 significant bits. Many decimal fractions have no finite binary expansion, just as 1/3 has none in decimal. The value 0.1 is stored as the nearest representable binary fraction, which is slightly off.
print((0.1).as_integer_ratio())
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(sum([0.1] * 10) == 1.0)The output is:
(3602879701896397, 36028797018963968)
0.30000000000000004
False
Falseas_integer_ratio() shows the exact stored value: 3602879701896397 divided by 2 to the 55th power. Each of 0.1 and 0.2 carries a tiny error, and the errors do not cancel in the sum. The result lands on a different float than the one nearest to 0.3.
This is not a Python bug. Java, JavaScript, C, and most other languages behave the same way, because the hardware does the arithmetic.
What print() shows
Python prints the shortest decimal string that converts back to the same float. That is why print(0.1) shows 0.1 even though the stored value is not exactly one tenth. To see the exact stored value, pass the float to Decimal:
from decimal import Decimal
print(Decimal(0.1))This prints 0.1000000000000000055511151231257827021181583404541015625.
Other float limits
- Integers are exact in a float only up to 2**53. Beyond that, neighboring integers collapse onto the same float.
- Float spacing grows with magnitude, so a fixed error threshold that works near 1 fails near 1e15.
float("nan")is not equal to anything, including itself. Usemath.isnan()to test for it.- Operations can overflow to
infinstead of raising an error, for example1e308 * 10.
print(float(2**53 + 1) == float(2**53))
nan = float("nan")
print(nan == nan)
print(1e308 * 10)This prints True, False, and inf.
Comparing floats with math.isclose
Do not compare computed floats with ==. Ask whether they are close enough. math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) returns true when this holds:
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(1e10, 1e10 + 1))
print(math.isclose(1e-10, 0.0))
print(math.isclose(1e-10, 0.0, abs_tol=1e-9))
print(math.isclose(float("nan"), float("nan")))
print(math.isclose(float("inf"), float("inf")))The output is True, True, False, True, False, True.
The third line is the common gotcha. The relative tolerance scales with the larger of the two values. When one value is exactly 0, the relative part is 0 as well, so only a default abs_tol of 0 remains. Whenever one side can be zero, set abs_tol to a value that makes sense for your data.
Choose tolerances from the problem. The default rel_tol of 1e-09 suits double-precision results with a few operations of error. Sensor data or iterative algorithms may need looser values.
Summing many floats
Repeated addition accumulates rounding error. math.fsum tracks the lost low-order bits and returns a correctly rounded total:
import math
values = [0.1] * 10
print(sum(values))
print(math.fsum(values))This prints 0.9999999999999999 and then 1.0.
Decimal: exact base-10 arithmetic
The decimal module stores numbers as base-10 digits, so 0.1 is exactly 0.1. Use it when the inputs are decimal by nature and results must match decimal arithmetic done by hand, as in money, invoices, and tax.
from decimal import Decimal
total = Decimal("0.1") + Decimal("0.2")
print(total)
print(total == Decimal("0.3"))
print(Decimal("1.10") + Decimal("2.205"))The output is 0.3, True, and 3.305.
Build Decimals from strings
Decimal(0.1) converts the already-inexact float, so it keeps the error. Decimal("0.1") parses the text and is exact. Integers are also safe: Decimal(5) is exact.
from decimal import Decimal
print(Decimal(0.1) == Decimal("0.1"))
print(Decimal("0.5") == 0.5)
print(Decimal("0.1") == 0.1)This prints False, True, False. 0.5 is a power of two, so it is exact in binary. 0.1 is not, so the comparison with the float fails.
Mixing with float
Arithmetic between Decimal and float raises TypeError, which prevents silent precision loss. Arithmetic with int is allowed.
from decimal import Decimal
print(Decimal("1.5") * 2)
try:
Decimal("1.1") + 1.1
except TypeError as e:
print("TypeError:", e)The first line prints 3.0. The second prints TypeError: unsupported operand type(s) for +: 'decimal.Decimal' and 'float'.
Precision and rounding
Decimal arithmetic uses a context. By default it keeps 28 significant digits, and +, -, *, and / round their results to that precision. Use localcontext() to change it for one block without affecting the rest of the program.
from decimal import Decimal, localcontext, ROUND_HALF_UP, ROUND_HALF_EVEN
with localcontext() as ctx:
ctx.prec = 6
print(Decimal(1) / Decimal(3))
price = Decimal("2.665")
cents = Decimal("0.01")
print(price.quantize(cents))
print(price.quantize(cents, rounding=ROUND_HALF_UP))
print(price.quantize(cents, rounding=ROUND_HALF_EVEN))
print(round(2.675, 2))The output is:
0.333333
2.66
2.67
2.66
2.67quantize() rounds to the exponent of its argument, here two decimal places. The default mode is ROUND_HALF_EVEN, which sends halves to the nearest even digit. Many accounting rules expect ROUND_HALF_UP, so set the mode explicitly when it matters. The last line shows a float surprise. 2.675 is stored slightly below 2.675, so round(2.675, 2) gives 2.67, not the 2.68 you might expect.
Choosing a numeric type
| Task | Good choice | Reason |
|---|---|---|
| Scientific computing, graphics, statistics | `float` | Fast, hardware-supported, errors are expected and small |
| Money, invoices, exact decimal rules | `Decimal` (built from strings) | Exact decimal digits and controllable rounding |
| Money in a fixed smallest unit | `int` (for example cents) | Exact and fast, but you must format and convert yourself |
| Counting, indexing, large exact values | `int` | Arbitrary size, no rounding |
Decimal is slower than float and has more setup. Use it only when decimal exactness is a requirement. Also note that Decimal does not remove all inexactness. Decimal(1) / Decimal(3) is still rounded, because one third has no finite decimal expansion.
Exercise
A shop adds 19.99 and 5.01 and must test whether the total equals 25.00. Show how to do this correctly with Decimal, and explain why Decimal("19.99") is preferred over Decimal(19.99).
Show answer
Write from decimal import Decimal and then Decimal("19.99") + Decimal("5.01") == Decimal("25.00"), which is True (Decimal compares by value, so 25.00 and 25 are equal). Decimal("19.99") parses the text and stores exactly 19.99. Decimal(19.99) first receives the float 19.99, which is already the nearest binary approximation, and copies that error into the Decimal, so the digits would be a long inexact expansion. If the values must stay floats, math.isclose(19.99 + 5.01, 25.0) is the safe comparison, and it needs no abs_tol because neither side is zero.
Exercise
Why does math.isclose(1e-12, 0.0) return False, and how do you change the call so it returns True for differences below 1e-9?
Show answer
With the default abstol of 0.0 and one side exactly 0, the allowed difference is max(reltol * 1e-12, 0.0), which is about 1e-21. The actual difference of 1e-12 is larger, so the result is False. Call math.isclose(1e-12, 0.0, abs_tol=1e-9), which is True because 1e-12 <= 1e-9.