Python中舍入浮点数的问题

时间:2011-08-31 04:35:11

标签: python numpy types floating-point 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

我错过了什么? a的dtype是float32,我需要更改吗?

2 个答案:

答案 0 :(得分:5)

尝试创建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

答案 1 :(得分: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