How to Compare Floats in pytest with approx
Uses pytest.approx to compare floating-point numbers with tolerance, avoiding precision issues.
pip install pytest
Python code
6 linesimport pytest
def test_float_addition():
result = 0.1 + 0.2
expected = 0.3
assert result == pytest.approx(expected)
Output
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
- Use `pytest.approx(expected, abs=1e-3)` for an absolute tolerance
- 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
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.