Python:如何计算单元格之间的距离?

2024-04-25 21:13:24 发布

您现在位置:Python中文网/ 问答频道 /正文

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

网格中的每个单元格都是介于024之间的数字

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

我必须计算细胞的xy位置之间的距离。你知道吗

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

但这不是正确的解决办法


Tags: andings网格距离foriscell
3条回答

你应该考虑坐标而不是单元号

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
           xi = int(i/gs)
           yi = i % gs
           xj = int(j/gs)
           yj = j % gs
           dist = r0 * (abs(xi-xj) + abs(yi-yj))
# 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

这是一种方法:

r = 100

grid = ((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))

def coord(n):
    for x, line in enumerate(grid):
        if n not in line:
            continue
        y = line.index(n)
        return x, y

def dist(n, m):
        xn, yn = coord(n)
        xm, ym = coord(m)
        return r * (abs(xn - xm) + abs(yn - ym))

print(dist(0, 3))  # 300
print(dist(2, 7))  # 100
print(dist(11, 19)) # 400

这个想法是先得到数字的坐标,然后计算“距离”。你知道吗

相关问题 更多 >