Hone

Lessons · Python · do not compare decimals with ==

Do not compare floats with ==

0.1 + 0.2 == 0.3 is False, because neither side is stored exactly. Compare floats with a tolerance: math.isclose.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

An 'if total == expected' check in a test or a reconciliation that fails on values that print identically is this, every time.

How to think about it

Ask whether the two values are close enough for the purpose, and say the tolerance: math.isclose(a, b, rel_tol=1e-9). For money, avoid floats altogether.

Worked example

print(0.1 + 0.2 == 0.3)
False.
print(0.1 + 0.2)
0.30000000000000004.
import math
The tolerant comparison lives here.
print(math.isclose(0.1 + 0.2, 0.3))
True.
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
True: the same idea by hand.

Your turn

Are the two measurements the same, allowing float error?

same = math.(a, b)

The trap

math.isclose(a, 0.0) is False for any tiny a, because a relative tolerance of zero is zero. Pass abs_tol when comparing against 0.

Practise do not compare decimals with == on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.