Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 38 ยท Tests and Assertions

Comparing Floats with approx

Understand why 0.1 + 0.2 is not 0.3, then use pytest.approx with relative and absolute tolerances to compare floats, lists, dicts, complex numbers and NumPy arrays.

Open a Python prompt and type 0.1 + 0.2 == 0.3. The answer is False. This is not a Python bug. Computers store most decimal fractions in binary, and 0.1 has no exact binary form, so tiny rounding errors creep into every floating-point calculation. A test that compares floats with == is therefore fragile: it can fail after a harmless refactor that changes the order of operations.

pytest provides pytest.approx so that you compare floats within a tolerance instead. It reads naturally, and the failure report shows exactly how far apart the numbers were.

The problem, then the fix

Python == versus approx

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first test fails because the sum is 0.30000000000000004. The second passes. The third still fails, and its report shows both the value and the allowed tolerance, so you see that approx is not a blanket "always true".

How the tolerance works

By default, approx(expected) accepts a difference of up to:

  • a relative tolerance of 1e-6 (one millionth of the expected value), or
  • an absolute tolerance of 1e-12,

whichever is larger. The relative part makes the check scale with the size of the number; the absolute part rescues comparisons close to zero, where a relative tolerance would be zero.

You can change either with keyword arguments:

Python rel and abs tolerances

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first test passes: for an expected value of one million, the default relative tolerance is 1e-6 * 1000000 = 1.0, so a difference of 0.5 is accepted. The second widens it. The third passes because abs=1e-6 allows a difference of one millionth. The fourth fails, because the expected value 0 has a relative tolerance of 0, so only the tiny absolute 1e-12 applies and 1e-9 is too far away. Always pass abs= when the expected value is zero.

Choose tolerances from the problem, not by making the test pass. Money in cents needs abs=0.005; a physics simulation might need rel=1e-3. Write a comment when the reason is not obvious.

Collections of numbers

approx works on sequences, dicts and NumPy arrays, comparing element by element:

Python approx with lists and dicts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The third report lists the index and size of the difference. Dict comparison requires the same keys on both sides; only the values are compared approximately.

Comparing with an expected value everywhere

approx wraps the expected value. Writing it on either side of == works, but the convention is "actual == approx(expected)":

Python
assert compute_tax(100) == pytest.approx(21.0)

Compare with the standard library's math.isclose(a, b, rel_tol=..., abs_tol=...). It returns a boolean and gives no helpful report on failure, which is why approx is preferred in tests.

NumPy arrays and complex numbers

approx also handles NumPy arrays (shape must match) and complex numbers. Because Pyodide includes NumPy, you can try it right here:

Python approx with NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For heavy array work, NumPy's own numpy.testing.assert_allclose is also available; approx keeps your test style uniform.

What approx cannot do

  • It is not for integers or strings; use ==.
  • It does not make nan equal to nan. Pass nan_ok=True to allow it.
  • It does not compare ordering (>). approx(1.0) > 0.9 is not supported; compare the plain numbers.
  • A very wide tolerance hides real bugs. If you find yourself using rel=0.5, step back and ask what you are testing.
Python
assert float("nan") == pytest.approx(float("nan"), nan_ok=True)

Rounding as an alternative

Sometimes the cleanest test is to round the result to the precision you care about:

Python
assert round(total, 2) == 9.75

This is fine for display values such as currency, but approx is more robust and communicates intent better. Better still, avoid floats for money: use decimal.Decimal or integer cents, and compare exactly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does 0.1 + 0.2 == 0.3 evaluate to False in Python?

    Most decimal fractions have no exact binary representation, so results can differ from the exact decimal answer by tiny amounts.
  2. 2. What default tolerance does pytest.approx use?

    approx accepts the larger of a 1e-6 relative tolerance and a 1e-12 absolute tolerance.
  3. 3. You compare a tiny result with pytest.approx(0) and the test fails. Why?

    A relative tolerance scales with the expected value. For zero it is zero, so supply abs=.
  4. 4. Which values can pytest.approx compare element by element?

    approx wraps sequences, mappings and NumPy arrays and applies the tolerance to each element.

Summary

  • Never compare floating-point results with ==; use pytest.approx(expected).
  • The default tolerance is relative 1e-6 or absolute 1e-12, whichever is larger; set rel= and abs= when you need to.
  • Near zero you must pass abs=.
  • approx works for lists, dicts, complex numbers and NumPy arrays.
  • Use Decimal or integers for money; do not use approx for ints or strings.

Next: Testing Warnings, Output and Logs