brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's math.isclose compares floats that look equal but aren't

Python
~/tips/tip-python-math-isclose

import math

Compare floating point numbers safely instead of trusting the double equals sign.

Everyone hits this once: 0.1 + 0.2 == 0.3 is False in Python. It’s how floating point works in every language, and math.isclose is the clean way around it.

import math

print(0.1 + 0.2 == 0.3)                          # False
print(math.isclose(0.1 + 0.2, 0.3))              # True
print(math.isclose(1e-12, 0))                    # False
print(math.isclose(1e-12, 0, abs_tol=1e-9))      # True

By default it uses a relative tolerance of about nine digits, which suits most numbers you’d compare in a script, like temperatures or totals that went through a few calculations.

The third line is the part that catches people. A relative tolerance means “close compared to the size of the numbers”, and nothing is close to zero in relative terms. When one side can be zero, like checking that a balance ended at 0.0, add an absolute tolerance with abs_tol, as in the last line.

For money I wouldn’t use floats at all. decimal.Decimal or whole cents as integers avoid the problem instead of working around it. And in tests, pytest.approx does the same job with nicer error messages, so I’d keep isclose for normal code.

Further reading: math.isclose, Floating point arithmetic

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link