为什么我的Python haversine距离计算与在线工具和Google地图相比是错误的?
我正在用Python编写一个haversine距离和角度计算器,作为一个小型自主RC汽车项目的一部分。我的两个测试位置是为什么我的Python haversine距离计算与在线工具和Google地图相比是错误的?,python,haversine,Python,Haversine,我正在用Python编写一个haversine距离和角度计算器,作为一个小型自主RC汽车项目的一部分。我的两个测试位置是38.63594444,-90.2315和38.63594444,-90.232111111111 大多数在线计算器(以及我个人的TI-89)的计算距离约为0.05308公里。但是,我的Python函数的距离是0.06795公里。那大约有15米远,这是一个巨大的小钢筋混凝土车 我的轴承计算功能,points2angle,一直失败,直到我在toDegrees功能中进行了一些浮动铸
38.63594444,-90.2315
和38.63594444,-90.232111111111
大多数在线计算器(以及我个人的TI-89)的计算距离约为0.05308公里。但是,我的Python函数的距离是0.06795公里。那大约有15米远,这是一个巨大的小钢筋混凝土车
我的轴承计算功能,points2angle
,一直失败,直到我在toDegrees
功能中进行了一些浮动铸造。整数除法把我搞糊涂了
请注意,mypoints2angle
和points2distance
函数需要一个(度、分、秒)元组。这两个测试位置是该格式的(38,38,9.4),(-90,13,53.4)
和(38,38,9.4),(-90,13,55.6)
编辑:谢谢您的支持。我只是把纬度和经度弄混了。我修正了下面的点2Angle
代码,但在点2Distance
代码中留下了错误,因此我的错误代码和答案之间的区别仍然很清楚
我的距离计算(返回的距离错误):
我的十进制度数转换函数(工作):
您的经度和纬度混淆了,只需交换它们(或者如果在参数中交换了它们,则在参数中交换它们),就可以了:
def points2distance(start, end):
start_long = math.radians(toDegrees(start[1]))
start_latt = math.radians(toDegrees(start[0]))
end_long = math.radians(toDegrees(end[1]))
end_latt = math.radians(toDegrees(end[0]))
d_latt = float(end_latt - start_latt)
d_long = float(end_long - start_long)
a = (math.sin(d_latt/2)**2) + math.cos(start_latt) * math.cos(end_latt)* (math.sin(d_long/2)**2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return 6371 * c
points2distance([(38, 38, 9.4), (-90, 13, 53.4)], [(38, 38, 9.4), (-90, 13, 55.6)])
# returns: 0.053079628495340196
完美答案。然而,我现在已经破坏了我的
点2angle
计算,因为我想确保我已经修复了所有地方的混淆。将在我修复该问题时更新。非常感谢。更新:修复了我问题中的点2angle
计算。所以一切都正常,还是仍然存在差异?我很高兴能帮你这么多。:)是的,一切正常,我真的很感激。有时需要额外的一双眼睛!我确保在最初的帖子中将我的points2angle
代码更新为新的工作代码。结果我也错误地切换了代码中的所有变量。不过,现在一切都已解决。我希望我能投你的票,但我没有足够的代表。
def toDegrees(coord):
degrees = float(math.fabs(coord[0])) + float(coord[1]/60) + float(coord[2]/3600)
if coord[0] < 0:
degrees = degrees*-1
return degrees
def points2angle(start, end):
start_long = math.radians(toDegrees(start[1]))
start_latt = math.radians(toDegrees(start[0]))
end_long = math.radians(toDegrees(end[1]))
end_latt = math.radians(toDegrees(end[0]))
d_latt = end_latt - start_latt
d_long = end_long - start_long
y = math.sin(d_long)*math.sin(end_latt)
x = (math.cos(start_latt)*math.sin(end_latt)) - (math.sin(start_latt)*math.cos(end_latt)*math.cos(d_long))
brng = math.degrees(math.atan2(y,x))
compBear = (brng+360) % 360;
return compBear
def points2distance(start, end):
start_long = math.radians(toDegrees(start[1]))
start_latt = math.radians(toDegrees(start[0]))
end_long = math.radians(toDegrees(end[1]))
end_latt = math.radians(toDegrees(end[0]))
d_latt = float(end_latt - start_latt)
d_long = float(end_long - start_long)
a = (math.sin(d_latt/2)**2) + math.cos(start_latt) * math.cos(end_latt)* (math.sin(d_long/2)**2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
return 6371 * c
points2distance([(38, 38, 9.4), (-90, 13, 53.4)], [(38, 38, 9.4), (-90, 13, 55.6)])
# returns: 0.053079628495340196