Python Haversine公式度数远

时间:2019-03-05 02:05:19

标签: python

这是我所有的python代码,距离返回正确的距离很远。我分解了haversine公式,并知道它在C的某个地方出了问题。 C的数字太大,无法允许D返回正确的距离。

from math import sin, cos, atan2, sqrt, pi

First are my functions then my main part of the code
#-----FUNCTIONS------

#Header function
def Header():
    print("This program will calculate the distance between two geographic points!")

#get_location function
def Get_location():
    userLat = input("\n\n Please enter the latitude of your location in decimal degrees: ")
    userLon = input("Enter the longitude of the location in decimal degrees: ")
    return (userLat, userLon)


#Calculate distance function
#def Distance(lat1, lon1, lat2, lon2):
def Distance(location1, location2):
    radEarth = 6371 #km
    #location1 = Get_location()
    #location2 = Get_location()

    lat1 = location1[0]
    lon1 = location1[1]
    lat2 = location2[0]
    lon2 = location2[1]

    B = sin((lat1-lat2)/2)**2
    S = sin((lon1-lon2)/2)**2
    F = (cos(lat1))

    A = B + (F * (cos(lat2)) * S)


    C = 2 * (atan2(sqrt(A),sqrt(1-A)) * (180/pi))
    print(C)

    D = radEarth * C

    return D                                                       

This is the main part of my program

#-------MAIN---------

#Call header function
Header()

在用户继续时开始另一个循环:

doAnother = 'y'
while doAnother == 'y':

    #Collect location points from user
    location1 = Get_location()
    location2 = Get_location()
    print(location1)
    print(location2)
    #Calculate distance between locations
    distance = Distance(location1, location2)

    print('The distance between your two locations is: ' + str(distance))


    doAnother = raw_input('Do another (y/n)?'.lower())

#Display goodbye
print('Goodbye!')

1 个答案:

答案 0 :(得分:1)

您似乎正在执行here中所述的Haversine公式。 (顺便说一句,我必须做确切的事情。)您是正确的,C中存在问题。

您的代码(Python):

C = 2 * (atan2(sqrt(A),sqrt(1-A)) * (180/pi))

上面的URL中的代码(JavaScript):

var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

问题是您正在将C转换为度数(使用(180/pi)),但是下一个计算D = radEarth * C仅在C为弧度的情况下才有意义。