Search code examples
pythongpshaversine

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)


Solution

  • 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