Challenge - 5 Problems
Approximate Comparison Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of approximate float comparison with pytest.approx
What is the result of running this pytest assertion code snippet?
PyTest
import pytest def test_approx(): assert 0.1 + 0.2 == pytest.approx(0.3)
Attempts:
2 left
💡 Hint
Remember that floating point arithmetic can cause small precision errors, pytest.approx helps with that.
✗ Incorrect
The sum 0.1 + 0.2 is not exactly 0.3 due to floating point precision, but pytest.approx allows approximate equality, so the assertion passes.
❓ assertion
intermediate2:00remaining
Choosing the correct pytest.approx usage for relative tolerance
Which assertion correctly tests that variable x is approximately 10 with a relative tolerance of 1%?
Attempts:
2 left
💡 Hint
Check the parameter name for relative tolerance in pytest.approx.
✗ Incorrect
The rel parameter sets relative tolerance. abs sets absolute tolerance. tol is not a valid parameter.
🔧 Debug
advanced2:00remaining
Identify the error in pytest.approx usage
What error will this test raise when run?
PyTest
import pytest def test_value(): assert 5 == pytest.approx(5, rel=-0.1)
Attempts:
2 left
💡 Hint
Check the allowed range for relative tolerance values in pytest.approx.
✗ Incorrect
pytest.approx requires rel to be zero or positive. Negative values cause ValueError.
🧠 Conceptual
advanced2:00remaining
Understanding pytest.approx behavior with sequences
Given two lists a = [1.0, 2.0, 3.0] and b = [1.0, 2.01, 3.0], which pytest assertion will pass?
PyTest
import pytest a = [1.0, 2.0, 3.0] b = [1.0, 2.01, 3.0]
Attempts:
2 left
💡 Hint
Consider the difference between 2.0 and 2.01 and the tolerance values.
✗ Incorrect
Difference is 0.01. abs=0.02 allows difference up to 0.02, so assertion passes only with option C.
❓ framework
expert3:00remaining
Configuring pytest to globally change default tolerance for approx
How can you globally set pytest.approx to use a relative tolerance of 0.001 for all tests without changing each assertion?
Attempts:
2 left
💡 Hint
Think about how to customize pytest behavior programmatically.
✗ Incorrect
pytest does not support config files or env vars for approx tolerance. Overriding approx in conftest.py is the way to globally change behavior.