Assert numerical results with a tolerance
Floating-point calculations can produce a tiny rounding difference even when the algorithm is correct. pytest.approx describes the allowed numerical error instead of requiring identical binary representations. Its relative and absolute tolerances serve different roles, especially for values near zero.
A tolerance is part of the test's contract. Choose it from the calculation's accuracy requirements rather than enlarging it until a broken result passes. Approximate comparison does not make an invalid value valid, and NaN is not equal to an ordinary expected number. Keep exact comparisons for counts and other exact quantities.
import pytest
print(0.1 + 0.2 == pytest.approx(0.3))
print(1.01 == pytest.approx(1.0,
rel=0, abs=0.001))Your task
Implement close_to(actual,expected,tolerance) with pytest.approx, relative tolerance zero and the supplied absolute tolerance. Return a bool. Compare near-zero values correctly and reject NaN when expected is finite.
The explanation opens here once every check passes.