开发者

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]开发者_StackOverflow中文版: 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?


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


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


It does not work for me in cases the number is python's float or np.float64.

once I change the number to np.float32(), it works!

type(85.10000000000001), np.round(85.10000000000001,decimals=2), np.round(np.float32(85.10000000000001),decimals=2)

Results: (float, 85.10000000000001, 85.1)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜