欢迎访问宙启技术站
智能推送

Python计算GreatCircle距离的简单方法

发布时间:2024-01-04 17:24:31

Great Circle Distance 是指地球上两个点之间的最短距离,也被称为球面距离。计算球面距离的公式基于地球是一个球体的假设。在Python中,可以使用haversine公式来计算两个点之间的Great Circle Distance。

haversine公式的公式如下:

a = sin2(Δφ/2) + cos(φ1) * cos(φ2) * sin2(Δλ/2)

c = 2 * atan2(√a, √(1-a))

d = R * c

其中,φ1和φ2是两个点的纬度,Δφ是纬度之间的差异,λ1和λ2是两个点的经度,Δλ是经度之间的差异,R是地球的平均半径(通常为地球赤道的半径,约为6371公里)。

下面是一个简单的Python函数,用于计算两个点之间的Great Circle Distance:

import math

def great_circle_distance(lat1, lon1, lat2, lon2):
    # 将经纬度从度数转换为弧度
    phi1 = math.radians(lat1)
    phi2 = math.radians(lat2)
    delta_phi = math.radians(lat2 - lat1)
    delta_lambda = math.radians(lon2 - lon1)
    
    # 应用haversine公式计算Great Circle Distance
    a = math.sin(delta_phi/2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda/2)**2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    distance = 6371 * c  # 6371是地球赤道的半径,以公里为单位
    
    return distance

让我们看一个使用例子。假设我们有两个点的经纬度坐标:点A的经度为-73.9857,纬度为40.7486;点B的经度为-80.1918,纬度为25.7617。我们可以调用上述函数来计算这两个点之间的Great Circle Distance:

distance = great_circle_distance(40.7486, -73.9857, 25.7617, -80.1918)
print("Great Circle Distance between point A and point B:", distance, "km")

运行结果应该为:Great Circle Distance between point A and point B: 1736.9350009444566 km。

注意,以上代码中计算的Great Circle Distance是以千米为单位的。如果需要以其他单位(例如英里)表示,只需更改distance = 6371 * c 这一行代码中的乘法因子即可。

这是一个简单的方法来计算Great Circle Distance的例子,可以很方便地在Python中使用。