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: pytest.approx compares floats without the rounding surprise

Python
~/tips/tip-python-pytest-approx-floats

import pytest

Wrap the expected number in pytest.approx so tiny float errors do not fail the test.

Every first float test fails on 0.1 + 0.2 == 0.3, because the sum is slightly more than 0.3. pytest.approx exists for exactly this.

import pytest

def test_float():
    assert 0.1 + 0.2 == pytest.approx(0.3)

def test_rel():
    assert 1005 == pytest.approx(1000, rel=0.01)
    assert 3.14159 == pytest.approx(3.14, abs=0.01)

Both pass. By default the tolerance is a relative 1e-6, and rel= and abs= change it. When a check fails, the message shows both values and the tolerance. It also takes lists and dicts, so assert [0.1 + 0.2, 1.0] == pytest.approx([0.3, 1.0]) works as well.

The caveat is comparing with zero. A relative tolerance of zero is zero, so pytest falls back to an absolute tolerance of 1e-12. In a quick check, 1e-13 == pytest.approx(0) passed and 1e-6 == pytest.approx(0) failed with assert 1e-06 == 0 ± 1.0e-12. When the expected value is 0, pass an abs= that fits your data.

Failures are readable. On pytest 9.1.1, assert 0.3 == pytest.approx(0.31) reports assert 0.3 == 0.31 ± 3.1e-07 with the obtained and expected values below it. Dicts work as well: {"a": 0.1 + 0.2, "b": 1.0} == pytest.approx({"a": 0.3, "b": 1.0}) passed.

For the zero case, assert 1e-6 == pytest.approx(0, abs=1e-5) passes. NaN is another special case: float("nan") == pytest.approx(float("nan"), nan_ok=True) passes only with nan_ok=True, as the pytest reference describes.

Further reading: pytest.approx

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

Link