TExcelTAD
Home › Basic Math & Pre-Algebra › Floating Point

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, 13\frac{1}{3} 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: 12=0.12\frac{1}{2} = 0.1_2, 38=0.0112\frac{3}{8} = 0.011_2. But 110\frac{1}{10} has the factor 5 and repeats forever:

0.110=0.0001100110011001100110011…2(the block 0011 repeats)0.1_{10} = 0.0001100110011001100110011\ldots_2 \quad \text{(the block 0011 repeats)}

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:

python · try it yourself
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 exact
0.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.

value=(−1)sign×1.fraction2×2exponent−1023\text{value} = (-1)^{\text{sign}} \times 1.\text{fraction}_2 \times 2^{\text{exponent} - 1023}
text
 1 bit  sign
11 bits exponent  → range about 10⁻³⁰⁸ … 10³⁰⁸
52 bits fraction  → about 15–17 significant decimal digits

float.hex() shows the stored bits in hex. The repeating 9999… in 0.1 is the repeating 1001 pattern, rounded up in the last digit:

python · try it yourself
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 2.2×10−162.2 \times 10^{-16}, and beyond 2532^{53} it is larger than 1, so 253+12^{53} + 1 cannot be stored. Results too large to store become inf. And the error is relative: about 1 part in 101610^{16}, 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.

python · try it yourself
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

  • Decimal does base-10 arithmetic, so 0.1 is exact. Build it from a string, Decimal("0.1"), not from the float 0.1, which already carries the error. It is the right tool for money.
  • Fraction stores an exact ratio of two integers (see What a Fraction Is), so even 13\frac{1}{3} is exact.
python · try it yourself
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 value
True
72.5637 -> 72.56
3/10 1
3602879701896397/36028797018963968

The last line shows that the float 0.1 is really the fraction 3602879701896397255\frac{3602879701896397}{2^{55}}.

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 number type, so integers above 2532^{53} (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.approx or numpy.allclose instead 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, 13\frac{1}{3}, 12.5?

Answer

0.75, 0.0625 and 12.5 are exact; 0.2 and 13\frac{1}{3} are not.

Solution

A fraction terminates in binary only if its denominator in lowest terms is a power of two:

0.75=344=22exact0.2=155not exact0.0625=11616=24exact133not exact12.5=2522exact\begin{aligned} 0.75 &= \tfrac{3}{4} && 4 = 2^2 && \text{exact} \\ 0.2 &= \tfrac{1}{5} && 5 && \text{not exact} \\ 0.0625 &= \tfrac{1}{16} && 16 = 2^4 && \text{exact} \\ \tfrac{1}{3} & && 3 && \text{not exact} \\ 12.5 &= \tfrac{25}{2} && 2 && \text{exact} \end{aligned}
python · try it yourself
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 2542^{54}) show that 0.2 and 13\frac{1}{3} 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:

python · try it yourself
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
100.003=33.333…→ round down to 33.333×33.33=99.99→ 0.01 left over, give it to the last person\begin{aligned} \frac{100.00}{3} &= 33.333\ldots && \to\ \text{round down to } 33.33 \\ 3 \times 33.33 &= 99.99 && \to\ 0.01 \text{ left over, give it to the last person} \end{aligned}
python · try it yourself
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 N=2kN = 2^k such that float(N) + 1 == float(N) in Python.

Answer

N=253=9 007 199 254 740 992N = 2^{53} = 9\,007\,199\,254\,740\,992.

Solution

A double has 52 fraction bits plus the hidden leading 1, so it holds 53 significant bits. Below 2532^{53} the gap between floats is at most 1. At 2532^{53} the gap becomes 2, and N+1N + 1 lies exactly halfway between two floats. Ties round to the even neighbour, which is NN itself.

python · try it yourself
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?

  1. Python rounds every result to 16 digits
  2. 0.1, 0.2 and 0.3 have no exact binary representation, so tiny rounding errors appear
  3. Addition of floats is not commutative
  4. It is a known bug in CPython

Which is the safest way to create an exact decimal 0.1 for money calculations?

  1. Decimal(0.1)
  2. float("0.1")
  3. Decimal("0.1")
  4. round(0.1, 2)

Why does math.isclose(1e-12, 0.0) return False?

  1. The numbers are too large
  2. Its default tolerance is relative, and a relative tolerance around 0 is zero
  3. isclose only works on integers
  4. 1e-12 is not a valid float