Sub topic 6
Comparing floating-point numbers with pytest.approx
This chapter assumes you can write and run basic pytest tests with plain assert (covered earlier in this tutorial) and that you know what a float is in Python. It explains why exact float comparison fails, how pytest.approx decides two numbers are close enough, and where it can surprise you.
Why exact comparison fails
Python floats are binary fractions, and most decimal fractions have no exact binary form. Small errors appear in ordinary arithmetic:
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)The first line prints 0.30000000000000004, and the second prints False. The error is tiny, but == demands an exact match.
The same problem hits your own code. With the total function from cart.py, a test like this fails:
# test_cart_exact.py
from cart import total
def test_total_exact():
assert total([0.1, 0.2]) == 0.3pytest's output shows assert 0.30000000000000004 == 0.3. The code is fine, and the test is wrong to expect bit-for-bit equality.
Using pytest.approx
pytest.approx(expected) returns an object that compares equal to any number close enough to expected. Put it on either side of ==:
# test_cart_approx.py
import pytest
from cart import total
def test_total_of_floats():
assert total([0.1, 0.2]) == pytest.approx(0.3)
def test_total_with_tax_is_close():
assert total([0.1, 0.2], tax_rate=0.5) == pytest.approx(0.45)When a comparison fails, pytest shows the expected value with its tolerance, in a form like 0.31 ± 3.1e-07. This tells you how strict the check was.
How the tolerance is chosen
By default approx uses two tolerances at once:
- A relative tolerance of
1e-6, meaning one millionth of the expected value. - An absolute tolerance of
1e-12.
Two numbers count as equal if their difference is within the larger of the two. The relative part scales with the number, so large values get a wider window. The absolute part covers values near zero, where a relative window would shrink to nothing.
Customizing rel and abs
Pass rel or abs to change the window:
import pytest
def test_custom_tolerances():
assert 100.4 == pytest.approx(100, abs=0.5)
assert 1005 == pytest.approx(1000, rel=0.01)
assert 1.0001 != pytest.approx(1.0)The rules for combining them are easy to misread:
- If you give only
abs, the relative tolerance is dropped entirely. The default1e-6no longer applies. - If you give only
rel, the default absolute tolerance of1e-12stays in force. - If you give both, the values are equal when either tolerance is met.
Choose tolerances from what the code computes. Money rounded to cents suits abs=0.005. A physics result with known measurement error suits a rel that matches that error. Avoid loosening the tolerance just to make a red test go green, because a loose check can hide a real bug.
Comparing against zero
A relative tolerance of a number times zero is zero. Only the absolute tolerance helps when the expected value is 0, and the default of 1e-12 is very small:
import pytest
def test_near_zero():
assert 1e-13 == pytest.approx(0)
assert 1e-3 != pytest.approx(0)
assert 1e-3 == pytest.approx(0, abs=1e-2)A common case is a computed difference that should be "nothing", such as a - b for two nearly equal quantities. When the expected value is zero, always decide on an explicit abs.
Sequences, dicts, and arrays
approx also accepts collections and compares element by element:
import pytest
def test_collections():
assert [0.1 + 0.2, 0.2 + 0.4] == pytest.approx([0.3, 0.6])
assert (0.1 + 0.2, 1.0) == pytest.approx((0.3, 1.0))
assert {"a": 0.1 + 0.2, "b": 1.0} == pytest.approx({"a": 0.3, "b": 1.0})The rules for each type:
| Type | Behavior |
|---|---|
| Number (`float`, `int`, `Decimal`) | Compared with the tolerance window |
| List or tuple | Same length required, compared in order |
| Dict | Same keys required, values compared with tolerance |
| NumPy array | Compared element by element, shapes must match |
| Set | Not supported, raises `TypeError` |
| Nested structure | Not supported, raises `TypeError` |
The same rel and abs apply to every element, so a single loose value affects the whole check. If one element needs a different tolerance, write a separate assertion for it.
Special values: nan and infinity
By default nan is never equal to anything, including itself, and approx follows that rule. If your code legitimately returns nan and you want to assert it, opt in:
import math
import pytest
def test_nan_handling():
assert float("nan") != pytest.approx(float("nan"))
assert float("nan") == pytest.approx(float("nan"), nan_ok=True)
assert math.inf == pytest.approx(math.inf)Infinity compares equal only to infinity of the same sign. No finite tolerance can bridge the gap to a finite number.
Common errors
- Using ordering operators.
approxsupports==and!=only. Writingassert x <= pytest.approx(0.3)raisesTypeError. To check an upper bound with slack, add the slack yourself:assert x <= 0.3 + 1e-9. - Wrapping the wrong side.
approx(a) == bandb == approx(a)both work, butapprox(a + b)wrapped around a whole expression hides what you meant. Keep the computed result on one side and a literal on the other. - Using approx on strings or other types.
approx("a")raisesTypeError. Use plain==for non-numeric data. - Forgetting it with
!=.assert x != pytest.approx(y)is a valid way to say "not close", and it is useful for confirming a change had an effect. - Choosing a tolerance that is too strict. A result accumulated from thousands of additions can drift further than
1e-6relative. Check the error you actually get before pickingrel.
Choosing between approx and exact checks
Use plain == when the result is exact by construction: integers, strings, and floats built from exactly representable values such as 0.5 or 2.0. Use approx when the value comes from division, powers, square roots, trig, or sums of decimal fractions. If you are unsure, approx costs nothing and documents the intent.
Exercise
Predict whether each assertion passes with the default tolerances, and explain why: (1) assert 1e-13 == pytest.approx(0), (2) assert 1e-3 == pytest.approx(0). Then change the second one so that it passes without changing the number 1e-3.
Show answer
(1) passes, because the difference is 1e-13, below the default absolute tolerance of 1e-12. (2) fails, because the relative tolerance of 0 times 1e-6 is zero, so only the absolute tolerance of 1e-12 applies and 1e-3 is far outside it. Fix it by setting an explicit absolute tolerance: assert 1e-3 == pytest.approx(0, abs=1e-2).
Exercise
Write a test for total([0.1, 0.2, 0.3]) from cart.py that expects 0.6 and does not fail because of floating-point error.
Show answer
assert total([0.1, 0.2, 0.3]) == pytest.approx(0.6). The sum is 0.6000000000000001, which falls inside the default relative tolerance of 1e-6, so the test passes where == 0.6 would fail.