为什么我的Python haversine距离计算与在线工具和Google地图相比是错误的?

2024-05-19 03:40:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个haversine距离和角度计算器,作为一个小型自治RC汽车项目的一部分。我的两个测试位置是38.63594444444444,-90.231538.63594444444444,-90.23211111111111。在

大多数在线计算器(和我个人的TI-89)的距离大约为0.05308公里。但是,我的Python函数的距离是0.06795公里。这是大约15米,这是一个巨大的小型钢筋混凝土车。在

我的方位计算函数points2angle一直失败,直到我在toDegrees函数中做了一些浮点运算。整数除法把我搞砸了。在

警告一下,我的points2anglepoints2distance函数需要一个元组(度、分、秒)。这两个测试位置是(38, 38, 9.4), (-90, 13, 53.4)和{}。在

编辑:感谢mseifer。我只是把经纬度搞混了。我修正了下面的points2angle代码,但在points2distance代码中留下了错误,所以我的错误代码和答案之间的区别仍然很明显。在

我的距离计算(返回的距离错误):

  def points2distance(start,  end):  
      start_long = math.radians(toDegrees(start[0]))  
      start_latt = math.radians(toDegrees(start[1]))  
      end_long = math.radians(toDegrees(end[0]))  
      end_latt = math.radians(toDegrees(end[1]))
      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 

我的十进制度数转换函数(工作):

^{pr2}$

我的方位角计算(工作):

^{3}$

Tags: 函数代码距离错误mathfloatstart计算器
1条回答
网友
1楼 · 发布于 2024-05-19 03:40:19

你的经度和纬度是混合的,只要交换它们(或者如果它们在参数中被交换了,那么在那里交换它们)就可以工作了:

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

相关问题 更多 >

    热门问题