Undesired rounding when subtracting numpy arrays in Python

I ran into a problem when python automatically rounds very small numbers (less than 1e-8) when subtracting an array from a single float. Take this example:

import numpy as np float(1) - np.array([1e-10, 1e-5]) 

Any thoughts on how to get python to not round? This makes me divide by zero in some cases and become a problem. The same problem occurs when subtracting from a numpy array.

+4
source share
2 answers

This is basically just repr numpy arrays that are fooling you.

Consider the above example:

 import numpy as np x = float(1) - np.array([1e-10, 1e-5]) print x print x[0] print x[0] == 1.0 

This gives:

 [ 1. 0.99999 ] 0.99999999999 False 

So, the first element is actually non-zero, it is just a beautiful print of numpy arrays that show it this way.

This can be controlled using numpy.set_printoptions .

Of course, numpy is funded using limited precision floats. The entire numpy point must be a memory container for arrays of similar data, so there is no equivalent to the decimal class in numpy.

However, 64-bit floats have a decent accuracy range. You will not encounter many problems with 1e-10 and 1e-5. If you need to, there is also a numpy.float128 dtype, but operations will be much slower than using your own floats.

+6
source

I assume that it all depends on the handling of very small floating-point numbers, Python, and the C base libraries, which at some point tend to decrease accuracy.

If you need this level of accuracy, imho you have to rely on something else, like numerical numbers, etc.

I do not know if there is anything for this, but if you could represent these numbers in a different way (for example, 1/10000000000 and 1/100000 ), and then calculate the floating point result only at the end of all calculations, you should avoid all these problems.

(Of course, you need some class that automatically processes fractional calculations to avoid overriding formulas, etc.)

+1
source

All Articles