Sub topic 8
Floating-point precision, math.isclose, and Decimal
This chapter assumes you can run Python code, use print(), and know the difference between int and float. It explains why float arithmetic gives surprising results and which tools to use instead.
Why 0.1 + 0.2 is not 0.3
A Python float stores a number in binary, as a fraction whose denominator is a power of two. The value 0.1 has no exact form in binary, just as 1/3 has no exact form in decimal. Python stores the closest value it can, and small errors appear when you combine such values.
import math
from decimal import Decimal
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))The output is False, True, True. The first line is False because the sum is slightly above 0.3. The other two lines show two ways to handle this.
Comparing floats with math.isclose
Do not compare computed floats with ==. Use math.isclose(a, b), which returns True when the two values are close enough.
By default it uses a relative tolerance of 1e-09. This means the values may differ by about a billionth of the larger one. That works well for most values, but it fails when one value is 0. Comparing 0.0 to 1e-12 with only a relative tolerance is False. In that case, add an absolute tolerance with abs_tol.
import math
print(math.isclose(1e-12, 0.0))
print(math.isclose(1e-12, 0.0, abs_tol=1e-9))
print(math.isclose(1_000_000.0, 1_000_000.1, rel_tol=1e-6))This prints False, True, True. Choose a tolerance that fits your data. A tolerance suited to meters may be wrong for nanometers.
Exact decimal arithmetic with Decimal
The decimal module provides Decimal, a type that stores decimal digits exactly. It suits money and other values where the digits you write must be the digits you get.
Build a Decimal from a string. If you build it from a float, you copy the float's error into it.
from decimal import Decimal
print(Decimal("0.1"))
print(Decimal(0.1))
print(Decimal("19.99") * 3)
print(Decimal("10") / Decimal("4"))The second line prints a long value that starts 0.1000000000000000055511151231257827.... That is the exact value of the float 0.1. The other lines print 59.97 and 2.5.
You can mix Decimal with int, but mixing it with float raises a TypeError. This is deliberate and keeps accidental float errors out of your exact values.
Float or Decimal?
| Need | Use | Reason |
|---|---|---|
| Money, invoices, exact decimal digits | `Decimal` | Results match hand calculation |
| Science, graphics, statistics | `float` | Fast, with hardware support |
| Counting, exact whole numbers | `int` | No rounding error at any size |
Decimal is slower than float, so use it where exactness matters and not everywhere.
Common errors
- Testing computed floats with
==or!=. - Writing
Decimal(0.1)when you meantDecimal("0.1"). - Using
math.iscloseagainst 0 without settingabs_tol. - Adding a
Decimaland afloatin the same expression.
Exercise
You compute total = 0.1 + 0.2 and need to check that it equals 0.3. Which expression is correct, and why not total == 0.3?
Show answer
Use math.isclose(total, 0.3). The sum is stored as a binary approximation slightly above 0.3, so total == 0.3 is False. isclose accepts values within a small tolerance.
Exercise
What is the difference between Decimal("0.1") and Decimal(0.1), and which should you use for prices?
Show answer
Decimal("0.1") is exactly one tenth. Decimal(0.1) copies the float's binary approximation, which has many extra digits. Use the string form for prices.