Haversine formula in Python

The “great circle distance”, or Haversine formula, approximates the distance between two locations over the curve of a sphere, given the sphere’s radius. The sphere we are interested in here is the Earth – which is not a perfect sphere, but close enough for the approximations that we are interested in. One application of this formula is to help determine a theoretical least amount of time to transmit a signal from one location to another over an electronic wire and/or fiber medium. Let’s say you wanted to determine the theoretical fastest way to send data from New York to Los Angeles (or vice versa). First, we would need to determine the distance between the cities. One could image a lossless fiber optic cable that stretched in a straight line between the two cities. But a straight line would actually go through the earth, which is not practical, so we would go over the surface of the earth. This may not be practical as well for many other reasons, but it helps establish a best-case theoretical baseline that we can compare to actual network latency tests.

The Haversine formula is described in a Wikipedia article here: https://en.wikipedia.org/wiki/Haversine_formula. We would like to use this formula in some Python applications to help determine the great circle distance between geographical locations. The two variable pieces of information we will need are the locations, expressed in latitude and longitude in units of decimal degrees. We want a return value in units of kilometers.

Our formula will look something like this

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

def greatCircleDistanceInKM(latA, lonA, latB, lonB):
    lonA, latA, lonB, latB = map(radians, [lonA, latA, lonB, latB])
    return int(12734 * asin(sqrt(
      sin((latB-latA)/2)**2+cos(latA)*cos(latB)*sin((lonB-lonA)/2)**2)))

# Dodger stadium homeplate
latA = 34.073436
lonA = -118.240215

# Yankee stadium homeplate
latB = 40.829491
lonB = -73.926957

print(greatCircleDistanceInKM(latA, lonA, latB, lonB))

In the function “greatCircleDistanceInKM”, first we convert our decimal degrees to radians. The return statement is a somewhat compressed version of the haversine formula implemented in python. “12734” is an approximate diameter of the earth in kilometers. In the example use, I provide coordinates from Dodger Stadium to Yankee stadium. The result is 3937 kilometers (2446 miles).

I’ve had to use this formula a few times in Python and C++ code. I’m just posting it here for future reference.

Also see “from geopy.distance import great_circle”. Use like this (requires installation of geopy)…

from geopy.distance import great_circle

coordA=(34.073436, -118.240215)
coordB=(40.829491, -73.926957)
print int(great_circle(coordA, coordB).kilometers)

Leave a Comment