通过比较不同的点来计算距离

时间:2017-10-13 15:44:32

标签: python-2.7

我有不同的位置,我需要计算它们之间的距离:

Location      Lat     Long     Distance
   A         -20      -50      (A-B)+(A-C)+(A-D)
   B         -20.3    -51      (B-A)+(B-C)+(B-D)
   C         -21      -50      (C-A)+(C-B)+(C-D)
   D         -20.8    -50.2    (D-A)+(D-B)+(D-C)

有人会认识我吗?

我正在使用这个等式来计算两点之间的距离,但我不知道如何计算几点之间的距离。

R = 6373.0
dist_lat=lat2-lat
dist_lon=long2-lon

a= np.sin(dist_lat/2)**2 + np.cos(lat) * np.cos(lat2) * np.sin(dist_lon/2)**2
b= 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
Dist= R * b

1 个答案:

答案 0 :(得分:0)

这是我第一次使用python,所以要小心,我也很快就做到了 - 这可能是错误的。

在python2.7上测试。

import numpy as np
import itertools as it

# these are the points
points = {
    'A' :{'lat':-20   ,'lon':-50}  
    ,'B':{'lat':-20.3 ,'lon':-51}  
    ,'C':{'lat':-21   ,'lon':-50}  
    ,'D':{'lat':-20.8 ,'lon':-50.2}  
}

# this calculates the distance beween two points
# basicly your formula wrapped in a function
# - used below
def distance(a, b):
    R = 6373.0
    dist_lat = a['lat']-b['lat']
    dist_lon = a['lon']-b['lon']

    x = np.sin(dist_lat/2)**2 + np.cos(b['lat']) * np.cos(a['lat']) * np.sin(dist_lon/2)**2
    y = 2 * np.arctan2(np.sqrt(x), np.sqrt(1 - x))
    return R * y


distances = {}

# produce the distance beween all combinations
# see: https://docs.python.org/2/library/itertools.html
# - uses above function
for x in it.combinations(points.keys(), 2):
    distances[ ''.join(x) ] = distance(points[x[0]],points[x[1]])

# for every starting point 
# - filter the distance it is involved in
# - sum
for CH in ('A','B','C','D'):
    print CH,' ', sum(dict((key,value) for key, value in distances.iteritems() if CH in key).values())

输出:

$ python2.7 test.py
A   6983.4634697
B   9375.21128818
C   5859.5650322
D   9472.23979008