Problems with rounding floating in Python

I have a problem with np.round, np.around where it is not being rounded properly. I canโ€™t include the code because when I do it manually, set the value (as opposed to using my data), the return works, but here is the output:

In [177]: a Out[177]: 0.0099999998 In [178]: np.round(a,2) Out[178]: 0.0099999998 In [179]: np.round(a,1) Out[179]: 0.0 

What am I missing? Dtype a is float32, do I need to change this?

+6
source share
2 answers

Try creating np.float32(0.01) and you will see the answer. You get accuracy that you can already.

 >>> import numpy as np >>> x = 0.01 >>> epsilon = 0.01 - np.float32(0.01) >>> for n in np.arange(x - 10*epsilon, x + 10*epsilon, epsilon): ... print(repr(np.float32(n))) ... 0.0099999979 0.0099999979 0.0099999979 0.0099999988 0.0099999988 0.0099999988 0.0099999988 0.0099999998 0.0099999998 0.0099999998 0.0099999998 0.0099999998 0.010000001 0.010000001 0.010000001 0.010000001 0.010000002 0.010000002 0.010000002 0.010000002 
+5
source

Notice that there is a problem with the python round and numpy.float64 . See the example below:

 In [88]: round(np.float64(16.259766999999947), 4) Out[88]: 16.259799999999998 

The only way to fix this is to convert numpy.float64 to float before using the round function, as shown below:

 In [89]: round(float(np.float64(16.259766999999947)), 4) Out[89]: 16.2598 
0
source

Source: https://habr.com/ru/post/896282/


All Articles