python - 如何在 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]))
解决方案
对于每个轴,您可以检查环绕时或不环绕时距离是否较短。考虑行轴,行i
和j
。
- 当不环绕时,区别是
abs(i - j)
。 - 环绕时,差异是“翻转”的,如
10 - abs(i - j)
. 在您的示例中i == 0
,j == 9
您可以检查这是否正确产生了 1 的距离。
然后只需取较小的那个:
delta_row = same[0][i] - 0 #row coord of centre
delta_row = min(delta_row, 10 - delta_row)
同样对于delta_column
.
最终dist[i]
计算无需更改。
推荐阅读
- python - 你如何在 Python 中使用 curve_fit?
- jasper-reports - Jaspersoft:Web 服务器不显示 HTML,但显示 PDF
- python - Python 使用 Skimage 和 PyQt5 显示 12 位 .tif 图像
- python - 在 python 3 中将图像文件编码为 multipart/form-data
- javascript - javascript:当我知道 id 时从数组中获取对象
- android - Android Espresso UI 测试 - 使用 Idling 资源等待屏幕上的元素
- java - Flutter:kotlin在java安装中找不到需要的jdk工具
- java - java-无法访问 ActiveX 应用程序“com.jacob.com.ComFailException: Can't get object clsid from progid”
- css - flex 不能使设计响应
- c - 试图用 c 中的 NULL 来理解内存泄漏