Numpy检查两个数组中的元素是否近似相等

5

我有两个包含浮点数值的numpy数组,我尝试查找数值近似相等(浮点比较)的索引。

所以需要做类似以下的操作:

x = np.random.rand(3)
y = np.random.rand(3)

x[2] = y[2]

# Do the comparison and it should return 2 as the index

我尝试了类似以下的东西:
np.where(np.allclose(x, y))

然而,这将返回一个空数组。如果我执行以下操作:
np.where(x == y)  # This is fine.

我尝试使用numpy.wherenumpy.allclose的组合,但无法使其工作。当然,我可以用循环来做,但那似乎很繁琐而且不符合Python风格。


4
尝试使用np.isclose代替np.allclose - Divakar
当然可以!我怎么会脑抽了呢。如果你把这个写成答案,我就可以接受它。 - Luca
2个回答

11

你要寻找的是np.isclose函数:

np.where(np.isclose(x, y))

我正在等待10分钟的时间过去。你们太快了,太敏锐了! - Luca

4

您可以始终使用以下内容:

np.where( np.abs(x-y) < epsilon )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接