首页 > 解决方案 > 如何在 Python 中实现一个函数来计算圆环上两个任意点之间的欧几里得距离

问题描述

给定一个随机填充数字的 10x10 网格(二维数组),要么0, 1要么2。考虑到周期性边界,如何找到两个给定点之间的欧几里得距离(距离向量的 l2 范数)?

让我们考虑一个称为 的任意网格点centre。现在,我想找到最近的网格点,其中包含与 相同的值centre。我需要考虑周期性边界,这样矩阵/网格可以被看作是一个圆环而不是一个平面。在这种情况下,假设centre = matrix[0,2],我们发现 中存在相同的数字matrix[9,2],这将位于矩阵的南边界。使用我的代码计算的欧几里得距离将用于此示例np.sqrt(0**2 + 9**2) = 9.0。但是,由于周期性边界,距离实际上应该是1,因为matrix[9,2]是 的北部邻居matrix[0,2]。因此,如果正确实现了周期性边界值,则不应存在幅度大于 8 的距离。

因此,我会对如何在 Python 中实现一个函数感兴趣,该函数通过对边界应用环绕来计算圆环上两个任意点之间的欧几里得距离。

import numpy as np

matrix = np.random.randint(0,3,(10,10))
centre = matrix[0,2]

#rewrite the centre to be the number 5 (to exclude itself as shortest distance)
matrix[0,2] = 5

#find the points where entries are same as centre
same = np.where((matrix == centre) == True)
idx_row, idx_col = same

#find distances from centre to all values which are of same value 
dist = np.zeros(len(same[0]))
for i in range(0,len(same[0])):
    delta_row = same[0][i] - 0 #row coord of centre
    delta_col = same[1][i] - 2 #col coord of centre
    dist[i] = np.sqrt(delta_row**2 + delta_col**2)

#retrieve the index of the smallest distance
idx = dist.argmin() 
print('Centre value: %i. The nearest cell with same value is at (%i,%i)' 
      % (centre, same[0][idx],same[1][idx]))

标签: pythonpython-3.xnumpymatrixeuclidean-distance

解决方案


对于每个轴,您可以检查环绕时或不环绕时距离是否较短。考虑行轴,行ij

  • 当不环绕时,区别是abs(i - j)
  • 环绕时,差异是“翻转”的,如10 - abs(i - j). 在您的示例中i == 0j == 9您可以检查这是否正确产生了 1 的距离。

然后只需取较小的那个:

delta_row = same[0][i] - 0 #row coord of centre
delta_row = min(delta_row, 10 - delta_row)

同样对于delta_column.

最终dist[i]计算无需更改。


推荐阅读