0
0
PyTesttesting~10 mins

Approximate comparisons (pytest.approx) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assert that 0.1 + 0.2 is approximately equal to 0.3 using pytest.approx.

PyTest
import pytest

def test_sum():
    assert 0.1 + 0.2 == [1]
Drag options to blanks, or click blank then click option'
Apytest.approx(0.3)
B0.3
Capprox(0.3)
D0.30000000000000004
Attempts:
3 left
💡 Hint
Common Mistakes
Using direct equality (==) with floating points causes test failures due to precision errors.
Using a plain float instead of pytest.approx for approximate comparison.
2fill in blank
medium

Complete the code to assert that the list [1.0, 2.0, 3.0] is approximately equal to [1.0, 2.0001, 3.0] using pytest.approx.

PyTest
import pytest

def test_list_approx():
    result = [1.0, 2.0, 3.0]
    expected = [1.0, 2.0001, 3.0]
    assert result == [1]
Drag options to blanks, or click blank then click option'
Apytest.approx(expected)
Bexpected
Capprox(expected)
Dexpected.approx()
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing lists directly without pytest.approx causes failures due to small differences.
Trying to call approx() without importing pytest.
3fill in blank
hard

Fix the error in the test by completing the code to compare floating point numbers approximately with a relative tolerance of 1e-3.

PyTest
import pytest

def test_relative_tolerance():
    value = 100.0
    expected = 100.1
    assert value == pytest.approx(expected, [1]=1e-3)
Drag options to blanks, or click blank then click option'
Aabs
Brelative
Crel
Drel_tol
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'abs' instead of 'rel' for relative tolerance.
Using 'rel_tol' or 'relative' which are not valid pytest.approx parameters.
4fill in blank
hard

Fill both blanks to assert that 0.123456 is approximately equal to 0.123 with an absolute tolerance of 1e-3.

PyTest
import pytest

def test_absolute_tolerance():
    assert 0.123456 == pytest.approx(0.123, [1]=[2])
Drag options to blanks, or click blank then click option'
Aabs
Brel
C1e-3
D1e-4
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'rel' instead of 'abs' for absolute tolerance.
Setting tolerance too small to allow the difference.
5fill in blank
hard

Fill all three blanks to assert that the dictionary {'a': 1.0, 'b': 2.0} is approximately equal to {'a': 1.001, 'b': 2.002} with relative tolerance 1e-2 and absolute tolerance 1e-4.

PyTest
import pytest

def test_dict_approx():
    result = {'a': 1.0, 'b': 2.0}
    expected = {'a': 1.001, 'b': 2.002}
    assert result == pytest.approx(expected, [1]=[2], [3]=[4])
Drag options to blanks, or click blank then click option'
Arel
Babs
C1e-2
D1e-4
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping 'rel' and 'abs' keywords.
Using incorrect tolerance values causing test failures.