Problems with Rounding Floats in Python

别说谁变了你拦得住时间么 提交于 2019-12-12 08:46:19

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/7252581/problems-with-rounding-floats-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!