【问题标题】:Calculating round trip distance in python在python中计算往返距离
【发布时间】:2013-02-12 22:30:22
【问题描述】:

我的任务是计算从开始地点到我从 Facebook 抓取的所有活动地点的往返距离(以英里为单位),然后再回到起点。 到目前为止我的代码:

import json
import re
from urllib import urlopen
import math

def getLatRad(latitude):
    return float(latitude) * (math.pi/180.0)
def getLongRad(longitude):
    return float(longitude) * (math.pi/180.0)
tuplist =[]
finaltuplist = []
#start_latitude = float(input('Pls enter the latitude co-ordinate of your starting location:'))
#start_longitude = float(input('Pls enter the longitude co-ordinate of your starting location:'))
start_latitude = 41.721194054071
start_longitude = -73.934258235003
longRad1= getLongRad(start_longitude)
latRad1 = getLatRad(start_latitude)
def main():

    eventids = [
                '264100516989470',
                '129843580476568',
                '158475914271199',
               ]
    for event in eventids:
        f = urlopen('http://graph.facebook.com/%s' % event)
        d = json.load(f)
        name = d['name']
        longitude = d["venue"]["longitude"]
        latitude = d["venue"]["latitude"]
        tuplist.append((name,longitude,latitude))
    for coordinates in tuplist:
        longRad2= getLongRad(coordinates[1])
        latRad2= getLatRad(coordinates[2])
        dlon = longRad2 - longRad1 
        dlat = latRad2 - latRad1
        a = math.sin(dlat/2)**2 + math.cos(latRad1) * math.cos(latRad2) * math.sin(dlon/2)**2
        c = 2 * math.asin(math.sqrt(a)) 
        m = 3960 * c
        sum = m + m
        print sum
if __name__ == '__main__':
    main()

据我所知,这是我自己知道的。是否有人可以为我指出正确的方向以获得总往返距离,而不是与起始位置的各个距离?

【问题讨论】:

  • 您打算计算所有点的“最佳”往返距离、按特定顺序的往返,还是命中所有点的“任何”往返?
  • +1 表示 ybakos 的答案。旅行商问题,你需要想出一个启发式,对吧?
  • 我猜这些事件有一个日历排序(可能是 eventids 数组中的 id,所以在这个问题的上下文中没有“最佳”的概念。
  • 我需要像 endophage 说的那样通过日历排序来做到这一点
  • 所以,您可以确定活动时间表分开多长时间。如果两个事件相隔 2 小时,从事件 1 到事件 2 需要超过 2 小时,那么任何时间表都不可行,对吧?还是我们让它变得比想象的更复杂?

标签: python graph-algorithm


【解决方案1】:

因此,分解您的问题与您的解决方案。 目前你可以得到start和event1之间的距离,但是你不能得到event1和event2之间的距离。您还可以获取 start 和 event2 之间的距离。您需要在计算中更改什么以获得从 event1 到 event2 的距离?

编辑细化请求:

latRad1 = getLatRad(start_latitude) longRad1=getLongRad(start_longitude)

dlon = longRad2 - longRad1 a = math.sin(dlat/2)**2 + math.cos(latRad1) * math.cos(latRad2) * math.sin(dlon/2)**2

上面的 2 在你的 for 循环之外并且没有改变(我注意到了)。因此,当您移动到新位置计算距离时,您仍然会根据起始坐标进行计算。

【讨论】:

    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多