Value for epsilon in Python

Is there a standard value for (or a method to get) epsilon in Python? I need to compare floating point values ​​and compare them with the smallest possible difference.

In C ++, there is a function called numeric_limits::epsilon( ) , which gives the epsilon value for any given data type. Is there an equivalent in Python?

+49
python comparison floating-point epsilon
Mar 02 2018-12-12T00:
source share
4 answers

Information is available at sys.float_info , which corresponds to float.h on C99.

 >>> import sys >>> sys.float_info.epsilon 2.220446049250313e-16 
+103
Mar 02 2018-12-12T00:
source share

As strcat wrote, there is sys.float_info.epsilon .

But don't forget about the pitfalls of using it as an absolute error for floating point comparisons. For example. for large numbers, the rounding error may exceed epsilon.

If you think you need retraining, the standard reference is David Goldberg What every computer specialist should know about floating point arithmetic , or for a simpler overview, you can refer to the floating point guide .

+28
Mar 02 2018-12-12T00:
source share

Surprised no one mentioned it here; I think many people will use numpy.finfo (type (variable)). Eps instead. Or .resolution to evaluate accuracy.

Note that finfo is only for floating point types, and that it also works with Python's own float type (i.e., not limited to numpy types). The equivalent for integer types is iinfo , although it does not contain accurate information (because, well, why would that be?).

+2
Mar 02 '18 at 18:46
source share

If you cannot find a function for this, remember that the algorithm for calculating the accuracy of the machine is very simple (you can test it with your favorite programming language). For example, for python:

 eps = 1.0 while eps + 1 > 1: eps /= 2 eps *= 2 print("The machine precision is:", eps) 

In my case, I got:

The machine precision is: 2.220446049250313e-16

0
Aug 20 '19 at 18:10
source share



All Articles