0
0
PyTesttesting~10 mins

Approximate comparisons (pytest.approx) - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if a floating-point calculation result is approximately equal to an expected value using pytest.approx. It verifies that small differences due to floating-point precision do not cause the test to fail.

Test Code - pytest
PyTest
import pytest

def test_approximate_comparison():
    result = 0.1 + 0.2
    expected = 0.3
    assert result == pytest.approx(expected, rel=1e-9)
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls test_approximate_comparison functionFunction execution begins-PASS
3Calculates result = 0.1 + 0.2result variable holds floating-point sum 0.30000000000000004-PASS
4Compares result to expected using pytest.approx with relative tolerance 1e-9Comparison allows small floating-point differenceAssert result == pytest.approx(expected, rel=1e-9)PASS
5Test completes successfullyTest runner reports test passed-PASS
Failure Scenario
Failing Condition: The relative tolerance is set too low, causing the small floating-point difference to fail the comparison
Execution Trace Quiz - 3 Questions
Test your understanding
What does pytest.approx help with in this test?
AChecks if two strings are exactly equal
BSkips the test if values differ
CAllows comparison of floating-point numbers with a tolerance
DConverts numbers to integers before comparing
Key Result
Use pytest.approx to compare floating-point numbers approximately, avoiding false test failures caused by tiny precision differences.