繁体   English   中英

Python Haversine公式度数远

[英]Python haversine formula in degrees is way off

这是我所有的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!')

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

您的代码(Python):

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

来自上述网址的代码(JavaScript):

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

问题在于您正在将C转换为度数(具有(180/pi) ),但是下一次计算D = radEarth * C仅在数学上以C为弧度才有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM