Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 459
Gordon Wrigley Avatar asked Apr 08 '11 13:04

Gordon Wrigley


People also ask

What is a better way to compare floating point values?

To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

How do you check nearly equal in Python?

Python unittest – assertAlmostEqual() function assertAlmostEqual() in Python is a unittest library function that is used in unit testing to check whether two given values are almost equal or not. This function will take five parameters as input and return a boolean value depending upon the assert condition.

Can we use == to compare two float or double numbers?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.


2 Answers

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.

like image 150
Mark Ransom Avatar answered Sep 21 '22 16:09

Mark Ransom


Is something as simple as the following not good enough?

return abs(f1 - f2) <= allowed_error 
like image 35
Andrew White Avatar answered Sep 22 '22 16:09

Andrew White