runtime
247 / 500
question 247 Testing & Code Quality · medium

Close enough: comparing floats in tests

0.1 + 0.2 == 0.3 is False, so tests of money and measurements need a tolerance. Write close_enough(a, b, rel_tol=1e-9, abs_tol=0.0), following the rule Python's math.isclose uses: two numbers are close when their difference is at most rel_tol times the larger of their sizes, or at most abs_tol, whichever allows more. (Don't call math.isclose; write the rule.)

Functionclose_enough(a, b, rel_tol=1e-9, abs_tol=0.0)
Ruleabs(a - b) <= max(rel_tol × max(abs(a), abs(b)), abs_tol)
RaisesValueError if either tolerance is negative
Notethe rule is symmetric: swapping a and b never changes the answer
Examples
callclose_enough(0.30000000000000004, 0.3)returnsTrue
callclose_enough(100, 101, rel_tol=0.01)returnsTrue
callclose_enough(100, 102, rel_tol=0.01)returnsFalse
callclose_enough(0, 1e-12, abs_tol=1e-09)returnsTrue
callclose_enough(1, 1, rel_tol=-0.1)raisesValueError

Loading your progress…

Close enough: comparing floats in tests — Python practice · Runtime