Labs ICT
โญ Pro Login

Approximate Values with pytest.approx

Comparing floating-point numbers safely in tests.

Why Approximate Comparisons?

Floating-point arithmetic can produce unexpected results due to precision limitations. For example:

def test_float_issue():
    result = 0.1 + 0.2
    assert result == 0.3  # This FAILS!

# Result: 0.30000000000000004 != 0.3

pytest provides pytest.approx to handle these comparisons safely.

Using pytest.approx

Wrap the expected value with pytest.approx:

import pytest

def test_float_with_approx():
    result = 0.1 + 0.2
    assert result == pytest.approx(0.3)  # Passes!

Setting Tolerance

You can control the allowed tolerance:

def test_custom_tolerance():
    # Default tolerance is 1e-6
    assert 1.000001 == pytest.approx(1.0)

    # Set a specific tolerance
    assert 1.1 == pytest.approx(1.0, abs=0.2)

    # Relative tolerance
    assert 100.0 == pytest.approx(100, rel=0.01)

Working with Lists and Dictionaries

pytest.approx works with entire data structures:

def test_list_approx():
    result = [0.1 + 0.2, 0.3 + 0.4]
    assert result == pytest.approx([0.3, 0.7])

def test_dict_approx():
    result = {"a": 0.1 + 0.2, "b": 0.3 + 0.4}
    assert result == pytest.approx({"a": 0.3, "b": 0.7})

๐Ÿงช Quick Quiz

How do you compare floating-point numbers safely in pytest?