簡體   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