0
0
PyTesttesting~5 mins

Approximate comparisons (pytest.approx) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is pytest.approx used for in testing?

pytest.approx is used to compare floating-point numbers approximately, allowing small differences due to rounding errors.

Click to reveal answer
beginner
How do you write an assertion to check if result is approximately equal to 3.14 using pytest.approx?

Use assert result == pytest.approx(3.14) to allow a small tolerance in the comparison.

Click to reveal answer
intermediate
What are the two main ways to control tolerance in pytest.approx?

You can control tolerance by setting rel (relative tolerance) and abs (absolute tolerance) parameters.

Click to reveal answer
beginner
Why is approximate comparison important when testing floating-point numbers?

Because floating-point arithmetic can introduce tiny rounding errors, exact equality checks often fail. Approximate comparison avoids false test failures.

Click to reveal answer
intermediate
Can pytest.approx be used to compare lists or arrays of numbers?

Yes, pytest.approx supports comparing lists or arrays element-wise approximately.

Click to reveal answer
What does pytest.approx(1.0, rel=1e-3) mean?
AAccept values within 1% relative difference of 1.0
BAccept values within 0.001 absolute difference of 1.0
CAccept values within 0.1% relative difference of 1.0
DAccept values exactly equal to 1.0
Which of these is a correct way to assert approximate equality in pytest?
Aassert approx(x) == y
Bassert x == pytest.approx(y)
Cassert x.approx(y)
Dassert x.equals(y)
If you want to allow a fixed small difference regardless of value size, which parameter do you use?
Aabs
Brel
Ctol
Ddelta
What happens if you compare two floats with assert a == b and they differ by a tiny rounding error?
ATest raises an exception
BTest passes
CTest is skipped
DTest fails
Can pytest.approx be used to compare nested lists of floats?
ANo, only single floats
BOnly flat lists, not nested
CYes, it compares element-wise recursively
DOnly numpy arrays
Explain why approximate comparisons are needed when testing floating-point numbers.
Think about how computers store decimal numbers.
You got /4 concepts.
    Describe how to use pytest.approx to check if a value is close to 10 with a relative tolerance of 0.01.
    Use the rel parameter for relative tolerance.
    You got /3 concepts.