Assert approximate equality with pytest

Compare floating-point results with pytest.approx, choose meaningful tolerances, and handle sequences, dictionaries, NumPy arrays, and NaN.

Best practices
Assert approximate equality with pytest illustration

Use pytest.approx() when rounding error makes exact equality unsuitable for a numerical result. Choose a tolerance that reflects the calculation’s requirements rather than accepting an arbitrary discrepancy.

import pytest

assert 0.1 + 0.2 == pytest.approx(0.3)
assert 3.14159 == pytest.approx(3.14, rel=1e-2)
assert 3.14159 == pytest.approx(3.14, abs=0.01)

Exact equality remains appropriate for values that are supposed to match exactly. The point is to allow justified numerical error, not to relax every assertion involving a float.

Understand the tolerance

By default, approx uses relative tolerance 1e-6 and absolute tolerance 1e-12. The absolute allowance matters near zero. When you specify abs without rel, only the explicit absolute tolerance is used. When both are specified, meeting either is enough. Relative tolerance is calculated against the expected value passed to approx.

Compare collections

import pytest
import numpy as np

assert [0.1 + 0.2, 2.0] == pytest.approx([0.3, 2.0])
assert {'pi': 3.14159} == pytest.approx({'pi': 3.14}, rel=1e-3)
assert np.array([0.1 + 0.2, 2.0]) == pytest.approx(np.array([0.3, 2.0]))

Use corresponding ordered sequences or dictionaries with matching keys. Unordered sets cannot establish element correspondence. For more specialized array comparisons, NumPy’s testing helpers may fit better.

The unittest alternative

Inside a unittest.TestCase, these are alternatives:

self.assertAlmostEqual(result, 3.14, places=2)
self.assertAlmostEqual(result, 3.14, delta=0.01)

places rounds the difference to the requested decimal places; it does not compare formatted decimal strings or significant digits. delta supplies an absolute difference threshold. Do not supply both at once.

FAQ

Can I assert that values are not approximately equal?

Yes: assert actual != pytest.approx(expected). Use equality or inequality; ordering comparisons such as < pytest.approx(...) are not supported.

What about NaN?

NaN does not match by default. Use pytest.approx(float('nan'), nan_ok=True) when missing-value equality is intentionally part of the test. Infinity only matches the same infinity.

See pytest.approx reference.

Get a tailored plan

Contact us

Join the community

Scan with WeChat
to join the community

Try Guance

Start online and pay only for what you use.

Get started

Choose a Guance plan

Code hosting