Skip to content
Tactiverge

Python reference

Floating-point rounding and comparison

Also called: 0.1 + 0.2 · math.isclose · float error · epsilon

Definition

Most decimal fractions cannot be stored exactly in binary floating point, so tiny rounding errors appear and == between floats is unreliable.

Picture it

0.1 in binary is a repeating fraction, like 1/3 in decimal, so it gets rounded. Adding rounded numbers accumulates error. Compare floats with a tolerance instead: math.isclose(a, b, rel_tol=1e-9) or abs(a − b) < tol.

The maths

|a − b| ≤ max(rel_tol × max(|a|, |b|), abs_tol)
SI units used in this entry
QuantityUnitSymbol
ratiodimensionless1

Worked example

In Python, 0.1 + 0.2 == 0.3 is False. How big is the difference, and does math.isclose say they are equal?

  1. 0.1 + 0.2 = 0.30000000000000004
  2. Difference ≈ 5.55 × 10^-17
  3. isclose with the default rel_tol = 1e-9 → True

AnswerThe difference is about 5.55e-17; math.isclose returns True.

✓ The number in this answer is recomputed from scratch by an automated test.

In Python

import math
print(0.1 + 0.2 == 0.3)              # False
print(math.isclose(0.1 + 0.2, 0.3))  # True

Common misconceptions

  • Misconception: Floating-point error is not a Python bug; every language using IEEE 754 doubles does the same.
  • Misconception: Rounding before comparing (round(x, 2) == y) can still fail at boundaries; use a tolerance.