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 mathThe 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)
Solve one with the tests running
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.