计算地球上两个坐标之间的距离

时间:2016-03-29 09:55:31

标签: python coordinates distance coordinate-systems

我将90°0′0″N 0°0′0″E形式的两个坐标对作为字符串,并想要计算半径为R = 6371km的球体上这些点之间的距离。

我在网上发现了两个公式here,“半身像”和“余弦球面定律”,但它们似乎没有用。对于应返回2*pi*R / 4的90°角,半正弦运算正确,但余弦失败并返回0.具有更多随机坐标的不同点返回两个算法的假值:半正弦太高而余弦也太大低。

我的实现是错误的还是我选择了不正确的算法?

我应该如何进行这些计算(坐标对地球表面的距离)呢?

(是的,我知道我还没有检查N / S和E / W,但测试的坐标都在东北半球。)

这是我的Python 3代码:

import math, re
R = 6371
PAT = r'(\d+)°(\d+)′(\d+)″([NSEW])'

def distance(first, second):
    def coords_to_rads(s):  
        return [math.radians(int(d) +int(m)/60 +int(s)/3600) \
                for d, m, s, nswe in re.findall(PAT, s)]

    y1, x1 = coords_to_rads(first)
    y2, x2 = coords_to_rads(second)  
    dx = x1 - x2  
    dy = y1 - y2  

    print("coord string:", first, "|", second)
    print("coord radians:", y1, x1, "|", y2, x2)
    print("x/y-distances:", dy, dx)

    a = math.sin(dx/2)**2 + math.cos(x1) * math.cos(x2) * math.sin(dy/2)**2  
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))  
    haversine =  R * c  

    law_of_cosines = math.acos( math.sin(x1) * math.sin(x2) + \
                                math.cos(x1) * math.cos(x2) ) * R

    print("HS:", round(haversine, 2), "LOC:", round(law_of_cosines, 2))

    return haversine
    #return law_of_cosines

if __name__ == '__main__':
    def test(result, correct):
        print("result: ", result)
        print("correct:", correct)

    test(distance("90°0′0″N 0°0′0″E", "0°0′0″N, 0°0′0″E"), 10007.5)
    test(distance("51°28′48″N 0°0′0″E", "46°12′0″N, 6°9′0″E"), 739.2)
    test(distance("90°0′0″N 0°0′0″E", "90°0′0″S, 0°0′0″W"), 20015.1)
    test(distance("33°51′31″S, 151°12′51″E", "40°46′22″N 73°59′3″W"), 15990.2)

这是一些输出:

coord string: 90°0′0″N 0°0′0″E | 0°0′0″N, 0°0′0″E
coord radians: 1.5707963267948966 0.0 | 0.0 0.0
x/y-distances: 1.5707963267948966 0.0
HS: 10007.54 LOC: 0.0
result: 10007.543398010286
correct: 10007.5

coord string: 51°28′48″N 0°0′0″E | 46°12′0″N, 6°9′0″E
coord radians: 0.8984954989266809 0.0 | 0.8063421144213803 0.10733774899765128
x/y-distances: 0.09215338450530064 -0.10733774899765128
HS: 900.57 LOC: 683.85
result: 900.5669567853056
correct: 739.2

1 个答案:

答案 0 :(得分:1)

您在计算x时似乎混淆了ya。您应该使用纬度(y)的余弦,而不是经度(x)。

我通过将您的distance更改为angular_distance(即不要乘以R)并添加一些其他测试来发现这一点:

test(angular_distance("90°0′0″N 0°0′0″E", "89°0′0″N, 0°0′0″E"), math.radians(1))
test(angular_distance("90°0′0″N 0°0′0″E", "80°0′0″N, 0°0′0″E"), math.radians(10))
test(angular_distance("90°0′0″N 0°0′0″E", "50°0′0″N, 0°0′0″E"), math.radians(40))
test(angular_distance("90°0′0″N 0°0′0″E", "50°0′0″N, 20°0′0″E"), math.radians(40))