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
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.
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.
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.
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
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With