我目前正在使用 numpy float 数组。
我的问题是我想将它们与小数点后 3 位进行比较。
但是当我尝试使用 round 或 around 时,它不起作用。
如果您知道一种方法,我将非常感激。
这是我尝试过的代码
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
设置绝对精度参数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
这将允许您放弃对 .all()
这将比较数字之间的绝对差是否低于您的精度要求,因此在本例中低于 0.001
。这与四舍五入(或下限)略有不同,但由于您期望问题中的数据匹配,所以我认为这实际上就是您的意思。
关于python - numpy 循环比较数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61726644/