Mdomin45
Mdomin45

Reputation: 470

Why is this Python Haversine formula producing incorrect answers?

I found this code on stack overflow:

from math import radians, cos, sin, asin, sqrt, atan2

def haversine(lon1, lat1, lon2, lat2):
        """
        Calculate the great circle distance between two points 
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians 
        lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

        print(lon1, lat1, lon2, lat2)

        # haversine formula 
        dlon = abs(lon2 - lon1) 
        dlat = abs(lat2 - lat1) 
        a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
        c = 2 * atan2(sqrt(a), sqrt(1-a)) 
        r = 6371 # Radius of earth in kilometers. Use 3956 for miles
        return c * r

When I use the function with these coordinates: haversine(-94.5930, 39.1230, -94.4839, 39.1561), it returns 10.103458011601726.

When I run those coordinates through online gps coordinate distance calculators, they all produce an answer around 12 kilometers.

I can't find any differences between this code and the haversine formula found here, so I do not know why it is producing answers different than those from the online calculators (including the one in the link)

Upvotes: 1

Views: 2213

Answers (2)

Nicos Mouzourss
Nicos Mouzourss

Reputation: 11

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

# approximate radius of earth in km
R = 6373.0

lat1 = radians(-94.5930)
lon1 = radians(39.1230)
lat2 = radians(-94.4839)
lon2 = radians( 39.1561)

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)

Result: 12.138670702897617

Upvotes: 0

roganjosh
roganjosh

Reputation: 13185

Between your online validation and the use of your function, you are mixing up the order of latitude and longitude. This function expects it in lon/lat pairs, while lat/long is the more typical ordering of pairs. Your observation is repeatable if you enter them incorrectly online here.

print haversine(-94.5930, 39.1230, -94.4839, 39.1561) # 10.1034580116
print haversine(39.1230, -94.5930, 39.1561, -94.4839) # 12.1348612974

Upvotes: 3

Related Questions