Skip to the workspace
Pebellslearn by building
Floating Point Math  ›  Capstone Project

Comparing and Adding Floats Safely

Floating Point Math 12 minBecause float results carry small rounding errors, compare them with a tolerance rather than exact equality, keep money in whole units such as cents, and beware adding tiny values to huge ones.

computer science / Comparing and Adding Floats Safely

Explore each scene at your own pace.

01 · The rule

The rule

Comparing and Adding Floats Safely

A test checks that a discount brings a price to 0.3 and fails with "expected 0.3, got 0.30000000000000004". A physics simulation adds a tiny time step to a huge clock value and the clock stops moving. Both have the same cause: every float result is slightly rounded. You cannot remove the rounding, but you can write code that is not fooled by it.

The rule

Never ask floats for exact equality; ask whether they are close enough.

Instead of a == b, check whether the difference is smaller than a tolerance:

abs(a - b) < 1e-9          # absolute tolerance
math.isclose(a, b)         # Python: relative tolerance, scales with size

An absolute tolerance like 1e-9 suits numbers near 1. For very large or very small numbers, a relative tolerance (a fraction of the numbers' size) works better, which is what math.isclose does by default.

Three more habits follow from the same rule:

  • Money in whole units. Store 1999 cents, not 19.99 dollars. Integer addition is exact. Many languages also offer a decimal type for this.
  • Big plus tiny loses the tiny. Near 10¹⁶, neighbouring doubles are 2 apart, so 1e16 + 1 rounds straight back to 1e16. Adding many small values to a huge one can lose them all.
  • Order matters. Float addition is not perfectly associative: (a + b) + c can differ slightly from a + (b + c). Summing small values first, or using math.fsum, reduces error.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.