首页 > 解决方案 > Python:如何计算细胞之间的距离?

问题描述

假设我想计算方形网格中单元格之间的距离5x5。两个细胞之间的距离是100m

网格的每个单元格都是介于0和之间的数字24

0   1  2  3  4
5   6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24 

例如:

distance between cell 0 and 3 is 300
distance between cell 2 and 7 is 100
distance between cell 11 and 19 is 400

我必须计算细胞之间的距离x和位置的不同。y

gs = 5 ## Cells per side
S = gs*gs ## Grid Size
r0 = 100 ## distance between two cells

for i in range(0, S):
    for j in range(0, S):
        if i == j: continue
        x = int(floor(i/gs))
        y = int(floor(j/gs))
        dist = x*r0 + abs(j-i)*r0

但这不是正确的解决方案

标签: python

解决方案


# n1, n2 = cell numbers
cellsize = 100.0
x1,x2 = n1%gs, n2%gs
y1,y2 = n1//gs, n2//gs
dist = sqrt( float(x1-x2)**2 + float(y1-y2)**2)  # pythagoras theorem
dist *= cellsize

推荐阅读