Floating Point
Type 0.1 + 0.2 into almost any programming language and you get 0.30000000000000004. This is not a bug in Python. Computers store non-integer numbers as binary floating point (the IEEE 754 standard), and most decimal fractions have no exact binary form. This lesson explains why, how big the errors are, and the tools for comparing floats safely or avoiding them: math.isclose, Decimal and Fraction.
Why 0.1 cannot be stored exactly
In base 10, never ends: 0.3333… (see Rounding and Repeating Decimals). A fraction has a finite decimal expansion only if its denominator has no prime factors other than 2 and 5, the prime factors of 10.
Base 2 has only the prime 2. So in binary only fractions with a power of two as denominator terminate: , . But has the factor 5 and repeats forever:
The computer has to cut it off somewhere, so the stored "0.1" is very slightly off. Decimal(0.1) shows the exact value that is really stored:
from decimal import Decimal
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(Decimal(0.1))
print(Decimal(0.2))
print(Decimal(0.3))
print(0.5 + 0.25 == 0.75) # powers of two are exact0.30000000000000004
False
0.1000000000000000055511151231257827021181583404541015625
0.200000000000000011102230246251565404236316680908203125
0.299999999999999988897769753748434595763683319091796875
True
Both 0.1 and 0.2 are stored slightly too large, and 0.3 slightly too small. The sum of the first two lands one step above the stored 0.3, so the comparison fails.
How a double is laid out
A Python float is an IEEE 754 double: 64 bits, like scientific notation in base 2.
1 bit sign
11 bits exponent → range about 10⁻³⁰⁸ … 10³⁰⁸
52 bits fraction → about 15–17 significant decimal digitsfloat.hex() shows the stored bits in hex. The repeating 9999… in 0.1 is the repeating 1001 pattern, rounded up in the last digit:
import sys
for x in [1.0, 0.5, 0.1, 3.75]:
print(f"{x:<5} {x.hex()}")
print("epsilon:", sys.float_info.epsilon) # gap between 1.0 and the next float
print("max:", sys.float_info.max)
print(2.0**53, 2.0**53 + 1) # integers stop being exact here
print(1e308 * 10, -1e308 * 10)1.0 0x1.0000000000000p+0
0.5 0x1.0000000000000p-1
0.1 0x1.999999999999ap-4
3.75 0x1.e000000000000p+1
epsilon: 2.220446049250313e-16
max: 1.7976931348623157e+308
9007199254740992.0 9007199254740992.0
inf -inf
Three facts stand out. The gap between neighbouring floats grows with their size: near 1 it is about , and beyond it is larger than 1, so cannot be stored. Results too large to store become inf. And the error is relative: about 1 part in , whatever the magnitude.
Comparing floats safely
Never test computed floats with ==. Ask instead whether they are close enough. math.isclose uses a relative tolerance (default rel_tol=1e-09). Near zero you need an absolute tolerance as well, because a relative tolerance of a tiny number is tinier still.
import math
total = 0.0
for _ in range(10):
total += 0.1 # ten rounding errors pile up
print(total, total == 1.0, math.isclose(total, 1.0))
print(sum([0.1] * 10), math.fsum([0.1] * 10)) # compensated sums
print(math.isclose(1e-12, 0.0)) # relative tolerance fails at 0
print(math.isclose(1e-12, 0.0, abs_tol=1e-9))
print(round(0.1 + 0.2, 10) == 0.3)0.9999999999999999 False True
1.0 1.0
False
True
True
Adding 0.1 ten times with += misses 1.0 by one step. Since Python 3.12 the built-in sum() of floats uses compensated summation, which tracks the lost low-order bits, so like math.fsum it returns 1.0 here. A plain loop in Python, or the same loop in most other languages, does not.
Exact alternatives: Decimal and Fraction
Decimaldoes base-10 arithmetic, so 0.1 is exact. Build it from a string,Decimal("0.1"), not from the float0.1, which already carries the error. It is the right tool for money.Fractionstores an exact ratio of two integers (see What a Fraction Is), so even is exact.
from decimal import Decimal, ROUND_HALF_UP
from fractions import Fraction
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))
price = Decimal("19.99") * 3 * Decimal("1.21") # 21% tax
print(price, "->", price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
print(Fraction(1, 10) + Fraction(2, 10), Fraction(1, 3) * 3)
print(Fraction(0.1)) # the float's true valueTrue
72.5637 -> 72.56
3/10 1
3602879701896397/36028797018963968
The last line shows that the float 0.1 is really the fraction .
In software
- Money: store cents as integers or use
Decimal. Summing a million float payments can drift by a few cents. - Games and physics: positions far from the origin lose precision. Open-world engines shift the origin near the player to avoid jittery motion (see Game Physics).
- Machine learning works on purpose with less precision: float32 (about 7 digits), and float16 or bfloat16 for neural network weights. LLMs are often quantized further to 8 or 4 bits to save memory.
- JavaScript has only doubles for its
numbertype, so integers above (Number.MAX_SAFE_INTEGER + 1) lose exactness. This is why IDs and cents are often sent as strings in JSON. - Tests: use
math.isclose,pytest.approxornumpy.allcloseinstead of==for float results.
Exercises
Exercise 1: Which are exact?
Which of these are stored exactly as binary floats: 0.75, 0.2, 0.0625, , 12.5?
Answer
0.75, 0.0625 and 12.5 are exact; 0.2 and are not.
Solution
A fraction terminates in binary only if its denominator in lowest terms is a power of two:
from fractions import Fraction
for x in [0.75, 0.2, 0.0625, 1/3, 12.5]:
print(x, Fraction(x).denominator)0.75 4
0.2 18014398509481984
0.0625 16
0.3333333333333333 18014398509481984
12.5 2
The huge denominators (both ) show that 0.2 and were rounded to the nearest float.
Exercise 2: Fix the loop
This loop is meant to stop at 1.0 but never does: x = 0.0; while x != 1.0: x += 0.1. Explain why and give two fixes.
Answer
After ten steps x is 0.9999999999999999, not 1.0, so != stays true forever. Fix it with an integer counter or with x < 1.0 - 1e-9 (or math.isclose).
Solution
Each += 0.1 adds a tiny rounding error, and after ten additions they no longer cancel. The cleanest fix counts in integers and divides:
xs = [i / 10 for i in range(11)]
print(xs[-1], xs[3])1.0 0.3
i / 10 is rounded once from an exact integer, so 3 / 10 gives the nearest float to 0.3. Repeated addition rounds ten times and the errors pile up.
Exercise 3: Split a bill
Three friends split a €100.00 bill. Using Decimal, compute each share rounded to cents and the leftover cent(s) so that the shares add up to exactly 100.00.
Answer
Shares 33.33, 33.33 and 33.34 (one leftover cent).
Solution
from decimal import Decimal, ROUND_DOWN
total = Decimal("100.00")
share = (total / 3).quantize(Decimal("0.01"), rounding=ROUND_DOWN)
shares = [share, share, total - 2 * share]
print(shares, sum(shares))[Decimal('33.33'), Decimal('33.33'), Decimal('33.34')] 100.00
Exercise 4: Where does +1 disappear?
Find the smallest power of two such that float(N) + 1 == float(N) in Python.
Answer
.
Solution
A double has 52 fraction bits plus the hidden leading 1, so it holds 53 significant bits. Below the gap between floats is at most 1. At the gap becomes 2, and lies exactly halfway between two floats. Ties round to the even neighbour, which is itself.
k = 0
while float(2**k) + 1 != float(2**k):
k += 1
print(k, 2**k)53 9007199254740992
Test yourself
Why is 0.1 + 0.2 != 0.3 in Python?
- Python rounds every result to 16 digits
- 0.1, 0.2 and 0.3 have no exact binary representation, so tiny rounding errors appear
- Addition of floats is not commutative
- It is a known bug in CPython
Which is the safest way to create an exact decimal 0.1 for money calculations?
- Decimal(0.1)
- float("0.1")
- Decimal("0.1")
- round(0.1, 2)
Why does math.isclose(1e-12, 0.0) return False?
- The numbers are too large
- Its default tolerance is relative, and a relative tolerance around 0 is zero
- isclose only works on integers
- 1e-12 is not a valid float