Wednesday, 4 April 2018

floating point - What is the best way to compare floats for almost-equality in Python?



It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.



For example:
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/



What is the recommended way to deal with this in Python?




Surely there is a standard library function for this somewhere?


Answer



Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485.



If you're using an earlier version of Python, the equivalent function is given in the documentation.



def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)



rel_tol is a relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference between them while still considering them equal.



abs_tol is an absolute tolerance that is applied as-is in all cases. If the difference is less than either of those tolerances, the values are considered equal.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...