Stuff that interests me.

# Posts tagged Python

## Calculating Distance

Mar 20th

The solution for calculating the distance between any two points on a sphere is an equation called the Haversine Formula. It can be used to estimate the distance between any two points on Earth using their latitude and longitude by making the assumption that the Earth is a perfect sphere. It isn’t, but for some applications the approximation is good enough.

Here’s an example calculating the distance of two points using Python:

def min( val1, val2 ): if val1 > val2: return val2 else: return val1 def haversine( lat1, lon1, lat2, lon2 ): dlat = math.radians( lat2 - lat1 ) dlon = math.radians( lon2 - lon1 ) a = math.sin(dlat/2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon/2)**2 return 2*math.asin(min(1,math.sqrt(a)))

Calculating the distance between Los Angeles and New York City in kilometers:

>>> haversine( 34.05, -118.24, 40.71, -74.00 ) * 6367 3933.5883159892405

Same example, miles this time:

>>> haversine( 34.05, -118.24, 40.71, -74.00 ) * 3956 2444.0514179446263