【问题标题】:How can I compare two arrays with different sizes but with some floats that are approximate? [Python3]如何比较两个大小不同但浮点数近似的数组? [Python3]
【发布时间】:2019-07-27 17:59:54
【问题描述】:

如何比较两个大小不同但浮点数近似的数组?例如:

# I have two arrays
a = np.array( [-2.83, -2.54, ..., 0.05, ..., 2.54, 2.83] )
b = np.array( [-3.0, -2.9, -2.8, ..., -0.1, 0.0, 0.1, ..., 2.9, 3.0] )
# wherein len( b ) > len( a )

我需要的是索引 where(考虑两个列表中的这两个值)

math.isclose( -2.54, -2.5, rel_tol=1e-1) == True

我需要的答案是这样的

list_of_index_of_b = [1, 5, ..., -2]

这里的list_of_index_of_b 是一个带有“坐标”的列表,其中b 的特定元素近似于a 的某个元素。并非a 的所有元素在b 中都有近似值。还: len(list_of_index_of_b) == len(a)

【问题讨论】:

  • len(list_of_index_of_b) == len(a) ?
  • 如果ab 不是太大,一个简单的方法是np.where(np.isclose(*np.ix_(a, b), rtol=1e-1))

标签: python-3.x numpy floating-point compare precision


【解决方案1】:

您可以使用广播。这会在 ab 中的每个元素之间创建一个成对差异数组,然后您可以检查指定的容差。

当然,从复杂性的角度来看,这在计算上是低效的,因为您构造了一个大小为 |a|*|b| 的数组,并将每个成对距离与容差进行比较,即使其中一个差异已经足够小。也就是说,如果 |a||b| 中的一个相对较小,那么这种方法可能会非常快,因为它是纯 numpy 并且不需要循环。

a = np.array([1,5,6,7])
b = np.array([1.1,2,3,4.8,4.9,5,8])

rtol = 0.15

diff = a - b[:,None]
mask2d = (1/np.abs(b))*np.abs(a - b[:,None]) < rtol

mask = np.any(mask2d,axis=1)

这可以合并为一行:

indices = np.where(np.any((1/np.abs(b))*np.abs(a-b[:,None]) < rtol,axis=1))

【讨论】:

    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    相关资源
    最近更新 更多