Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with Rounding Floats in Python

I'm having a problem with np.round, np.around where it is not rounding properly. I can't include code, because when I do it manually set the value (as opposed to use the 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? The dtype of a is float32, do I need to change this?

like image 889
mike Avatar asked Aug 31 '11 04:08

mike


2 Answers

Try creating np.float32(0.01) and you will see your answer. You are getting the precision 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
like image 147
wim Avatar answered Sep 18 '22 16:09

wim


Note there seems to be an issue with python's round function and numpy.float64 types. See example below:

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

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

In [89]: round(float(np.float64(16.259766999999947)), 4)
Out[89]: 16.2598
like image 26
tsando Avatar answered Sep 18 '22 16:09

tsando