使用 numpy.floor() 对每 0.02 进行奇怪的舍入

Weird rounding using numpy.floor() to every 0.02

我无法弄清楚如何将一些数据四舍五入到每 0.02。这是我的代码:

def cpt_rnd(x):
    return np.floor(x*50)/50

x = np.array([32.16, 32.18, 32.2, 32.22])

d = cpt_rnd(x)
print(d)

哪个returns:

[32.14, 32.18, 32.2,  32.22]

缺少 32.16 - 它已向下舍入为 32.14

我注意到 ceil 和 floor 中的类似行为没有返回正确答案。这是使用 np.ceil 而不是

的输出
[32.16, 32.18, 32.22, 32.22]

在此示例中,应该先是 32.2,然后是 32.22,而不是重复 32.22。如有任何帮助,我们将不胜感激!

这是由于计算机上浮点数的有限分辨率导致在对它们执行算术运算时结果略微不准确 (Roundoff error caused by floating-point arithmetic)。您可以通过单独执行算法的各个部分来查看会发生什么:

>>> 32.16*50
1607.9999999999998

因此您看到这与 1608.0 的准确结果略有不同,应用 np.floor().

后将导致 1607.0

解决这个问题的方法是在 np.floor() 调用中放置一个 np.round(),即:

def cpt_rnd(x):
    return np.floor(np.round(x*50))/50

默认情况下,np.round() 四舍五入到最接近的整数,这正是我们在这里想要的。