我目前正在使用numpy浮点数组。
我的问题是,我想将它们与小数点后3位进行比较。
但是当我尝试使用圆形或环绕式时,它不起作用。
如果您知道一种方法,我将不胜感激。
这是我尝试的代码
import numpy as np
x = np.array(([0.32745, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)
y = np.array(([0.32788, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)
x = np.round(x, 3)
y = np.round(y, 3)
if (x == y).all():
print("ok")
在3个小数点处,0.32745向下舍入而0.32788向上舍入,因此它们不相等。一个更简单的解决方案可能是使用numpy的isclose
设置绝对精度参数isclose
:
atol
还有import numpy as np
decimal_points = 3
x = np.array(([0.32745, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)
y = np.array(([0.32788, -1.043, -0.633], [0.418, -1.038, -1.166]), dtype=float)
if np.isclose(x, y, atol=1e-decimal_points).all():
print("ok")
可以让您将呼叫转移到allclose
如果两个数字之间的绝对差小于您的精度要求,则将进行比较,因此在这种情况下,该值小于allclose
。这与四舍五入(或下限)有细微的区别,但是由于您希望问题中的数据能够匹配,因此我认为这实际上是您的意思。
您的基本想法是正确的,但是您的数据是错误的。
.all()
和0.001
中的第一个数字四舍五入为x
和y
,这就是为什么等式语句(正确)返回false的原因。尝试将它们四舍五入到小数点后两位,然后一切正常。
0.327