How to Compare Floats in pytest with approx

Uses pytest.approx to compare floating-point numbers with tolerance, avoiding precision issues.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 13 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

6 lines
Python 3.9+
import pytest

def test_float_addition():
    result = 0.1 + 0.2
    expected = 0.3
    assert result == pytest.approx(expected)

Output

stdout
No output — the test passes without error.

If run with `pytest -v`, the output includes:


test_float_comparison.py::test_float_addition PASSED

1 passed in 0.01s

How it works

pytest.approx compares floating-point values using a relative tolerance (default 1e-6) rather than exact equality, which is safer because binary floating-point arithmetic can produce tiny rounding errors (e.g., 0.1 + 0.2 == 0.30000000000000004). The expected value is wrapped inside approx, so pytest automatically applies the tolerance. The test passes because the difference between the actual result and expected value is within the allowed tolerance. This pattern is essential for any test involving floats, computations, or values derived from approximations.

Common mistakes

  • Using `==` for float comparisons instead of `approx`
  • Forgetting to import pytest before using pytest.approx
  • Not specifying a tight enough tolerance in production code
  • Comparing NaN values without custom handling, as approx fails on NaN by default

Variations

  1. Use `pytest.approx(expected, abs=1e-3)` for an absolute tolerance
  2. Use `pytest.approx(expected, rel=1e-9)` for a stricter relative tolerance

Real-world use cases

  • Testing arithmetic functions that return floating point results.
  • Verifying calculations in financial or scientific libraries.
  • Asserting values from APIs that return computed numeric measurements.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.