Compare two floats for equality in Python

When comparing two floats in Python, I see that the code is always like this to compare it with a small epsilon value, wondering what are the best methods for choosing the correct epsilon value? And what is the scene behind this? Thanks.

epsilon = 0.000001 abs(a - b)<epsilon 
+6
source share
4 answers

The answer is quite complicated, since you need to know how single or double precision floats ( Wikipedia ) are saved, usually thumb, you can use this table on Wikipedia as a reference for choosing epsilon. But there may be some exceptions, especially if you don’t know for sure whether it is float32 or float64 (or for Linux / Mac there are also float96 and float128).

But I think that the best practice would be to use some predefined function such as numpy_assert_array_almost_equal (numpy required).

I think that everyone processes it somehow differently, and while you can trust your results, each method has its pros and cons. And always keep in mind that floats can completely go away with incorrect arithmetic operations. those. when small differences of large values ​​are calculated. And ultimately, the value of epsilon depends on what accuracy you need and which should be tested there.

+3
source

There is an assert function in numpy for this purpose, which uses seven decimal values ​​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 
+4
source

What are the best methods for choosing the correct epsilon value?

It depends on the requirements of the application.

If he plans an Earth-bound re-launch trajectory for a spacecraft, I would choose a very small value, for example epsilon = (a+b) * 1e-15 .

If he predicts the US federal deficit (which by its nature has great uncertainty), there will probably be much more epsilon: epsilon = (a+b) * 0.002 .

+2
source

if you are looking for the best epsilon ever to get a better comparison, you can use python sys epsilon using :

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

but if you want this epsilon to be dynamically based on your a and b more, I would suggest going for:

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

or

 abs(ab) <= max( rel_tol * max(abs(a), abs(b)), abs_tol ) 
+1
source

All Articles