August 2018
Beginner
160 pages
4h 8m
English
Comparing floating point numbers can be tricky. For more details, go to: https://docs.python.org/3/tutorial/floatingpoint.html. Numbers that we consider equal in the real world are not so when represented by computer hardware:
>>> 0.1 + 0.2 == 0.3False
When writing tests, it is very common to compare the results produced by our code against what we expect as floating point values. As shown above, a simple == comparison often won't be sufficient. A common approach is to use a known tolerance instead and use abs to correctly deal with negative numbers:
def test_simple_math(): assert abs(0.1 + 0.2) - 0.3 < 0.0001
But besides being ugly and hard to understand, it is sometimes difficult to come up ...
Read now
Unlock full access