Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two floats for equality in Python [duplicate]

When comparing whether two float in Python, I see code always like this to compare for a small value epsilon, wondering what is the best practices to select the right epsilon value? And what is the scene behind it? Thanks.

epsilon = 0.000001
abs(a - b)<epsilon
like image 579
Lin Ma Avatar asked Oct 08 '15 19:10

Lin Ma


People also ask

Can we use == to compare two float values in Python?

In the case of floating-point numbers, the relational operator (==) does not produce correct output, this is due to the internal precision errors in rounding up floating-point numbers. In the above example, we can see the inaccuracy in comparing two floating-point numbers using “==” operator.

Is it possible to compare floats for equality in Python?

How To Compare Floats in Python. If abs(a - b) is smaller than some percentage of the larger of a or b , then a is considered sufficiently close to b to be "equal" to b . This percentage is called the relative tolerance. You can specify the relative tolerance with the rel_tol keyword argument of math.

Can we compare double with float?

Float has to round more than double, because it is smaller, so 1.1 rounded to the nearest valid Float is different to 1.1 rounded to the nearest valud Double.


2 Answers

There is an assert function in numpy for this purpose, which uses seven decimal precision by default.

from numpy.testing import assert_almost_equal

a = 0.000000001
b = 0.0000000001

>>> assert_almost_equal(a, b)
# Nothing returned.

b = 1
>>> assert_almost_equal(a, b)
AssertionError: 
Arrays are not almost equal to 7 decimals
 ACTUAL: 1e-09
 DESIRED: 1
like image 70
Alexander Avatar answered Sep 25 '22 06:09

Alexander


if you are looking for the best epsilon ever, to get best comparison you could use python's sys epsilon using:

>>> import sys
>>> sys.float_info.epsilon
2.220446049250313e-16

but if you are more looking to have this epsilon dynamically based on your a and b I would suggest go for:

abs(f1-f2) < tol*max(abs(f1),abs(f2))

or

abs(a-b) <= max( rel_tol * max(abs(a), abs(b)), abs_tol )
like image 24
user 12321 Avatar answered Sep 23 '22 06:09

user 12321