我在堆栈溢出上发现了这段代码:
from math import radians, cos, sin, asin, sqrt, atan2
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
print(lon1, lat1, lon2, lat2)
# haversine formula
dlon = abs(lon2 - lon1)
dlat = abs(lat2 - lat1)
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
当我使用具有以下坐标的函数时:havesine(-94.5930, 39.1230, -94.4839, 39.1561)
,它返回10.103458011601726
。
当我通过在线 GPS 坐标距离计算器运行这些坐标时,它们都会产生大约 12 公里的答案。
我找不到这段代码和发现的半正矢公式 here 之间的任何区别,所以我不知道为什么它产生的答案与在线计算器(包括链接中的答案)不同
最佳答案
在在线验证和使用函数之间,您混淆了纬度和经度的顺序。该函数期望它以经度/纬度对的形式出现,而纬度/经度是更典型的对的排序。如果您在线输入错误,您的观察结果是可重复的 here .
print haversine(-94.5930, 39.1230, -94.4839, 39.1561) # 10.1034580116
print haversine(39.1230, -94.5930, 39.1561, -94.4839) # 12.1348612974
关于python - 为什么这个 Python 半正矢公式会产生错误的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45216121/