为什么这个 Python Haversine 公式会产生错误的答案?
Why is this Python Haversine formula producing incorrect answers?
我在堆栈溢出时发现这段代码:
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
当我使用具有这些坐标的函数时:haversine(-94.5930, 39.1230, -94.4839, 39.1561)
,它 returns 10.103458011601726
.
当我通过在线gps坐标距离计算器运行这些坐标时,它们都给出了大约12公里的答案。
我找不到这段代码和 here 中的半正弦公式之间的任何区别,所以我不知道为什么它产生的答案与在线计算器(包括[中的那个)不同=23=])
在您的在线验证和使用您的功能之间,您混淆了纬度和经度的顺序。此函数需要 lon/lat 对,而 lat/long 是更典型的对顺序。如果您在网上输入错误,您的观察是可重复的 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
from math import sin, cos, sqrt, atan2, radians
# approximate radius of earth in km
R = 6373.0
lat1 = radians(-94.5930)
lon1 = radians(39.1230)
lat2 = radians(-94.4839)
lon2 = radians( 39.1561)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
print("Result:", distance)
结果:12.138670702897617
我在堆栈溢出时发现这段代码:
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
当我使用具有这些坐标的函数时:haversine(-94.5930, 39.1230, -94.4839, 39.1561)
,它 returns 10.103458011601726
.
当我通过在线gps坐标距离计算器运行这些坐标时,它们都给出了大约12公里的答案。
我找不到这段代码和 here 中的半正弦公式之间的任何区别,所以我不知道为什么它产生的答案与在线计算器(包括[中的那个)不同=23=])
在您的在线验证和使用您的功能之间,您混淆了纬度和经度的顺序。此函数需要 lon/lat 对,而 lat/long 是更典型的对顺序。如果您在网上输入错误,您的观察是可重复的 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
from math import sin, cos, sqrt, atan2, radians
# approximate radius of earth in km
R = 6373.0
lat1 = radians(-94.5930)
lon1 = radians(39.1230)
lat2 = radians(-94.4839)
lon2 = radians( 39.1561)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = R * c
print("Result:", distance)
结果:12.138670702897617