mik*_*ike 7 python floating-point types numpy rounding
我遇到了np.round,np.around的问题,它没有正确地舍入.我不能包含代码,因为当我手动设置值(而不是使用我的数据)时,返回有效,但这里是输出:
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
Run Code Online (Sandbox Code Playgroud)
我错过了什么?a的dtype是float32,我需要更改吗?
尝试创建np.float32(0.01),你会看到你的答案.你已经获得了精确度.
>>> 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
Run Code Online (Sandbox Code Playgroud)