Sometimes numbers are close but not exactly equal due to small differences. Approximate comparisons help check if values are close enough.
0
0
Approximate comparisons (pytest.approx)
Introduction
When testing calculations with floating point numbers that may have tiny rounding errors.
When comparing results from different machines or environments that produce slightly different outputs.
When checking values that come from measurements or sensors with small variations.
When you want to allow a small margin of error in your test assertions.
Syntax
PyTest
assert actual == pytest.approx(expected, rel=relative_tolerance, abs=absolute_tolerance)
expected is the value you want to compare against.
You can set rel for relative tolerance and abs for absolute tolerance to control how close values must be.
Examples
Checks if 0.1 + 0.2 is approximately equal to 0.3, allowing for small floating point errors.
PyTest
assert 0.1 + 0.2 == pytest.approx(0.3)
Allows a 1% relative difference between values.
PyTest
assert 100.0 == pytest.approx(100.1, rel=1e-2)
Allows an absolute difference of 0.001, useful for very small numbers.
PyTest
assert 0.0001 == pytest.approx(0.0, abs=1e-3)
Sample Program
This test checks three cases where values are close but not exactly equal. It uses pytest.approx to allow small differences.
PyTest
import pytest def test_approximate_comparison(): result = 0.1 + 0.2 expected = 0.3 assert result == pytest.approx(expected) # Test with relative tolerance value = 100.0 expected_value = 100.1 assert value == pytest.approx(expected_value, rel=1e-2) # Test with absolute tolerance small_value = 0.0001 zero = 0.0 assert small_value == pytest.approx(zero, abs=1e-3)
OutputSuccess
Important Notes
Use pytest.approx to avoid test failures caused by tiny floating point errors.
You can combine rel and abs to fine-tune how close values must be.
Approximate comparisons work for floats and sequences like lists or tuples of floats.
Summary
Approximate comparisons help test values that are close but not exactly equal.
Use pytest.approx with optional relative and absolute tolerances.
This avoids false test failures due to small rounding differences.