Implementing Haversine in Python
Haversine Distance Calculation
To implement the Haversine distance calculation in Python, you can use the following code:
import math
def haversine_distance(lat1, lon1, lat2, lon2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
## Convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
## Haversine formula
a = math.sin((lat2 - lat1) / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2
c = 2 * math.asin(math.sqrt(a))
r = 6371 ## Radius of earth in kilometers
return c * r
This function takes the latitude and longitude of two points as input, converts them to radians, and then calculates the Haversine distance using the formula. The result is the distance in kilometers.
Example Usage
You can use the haversine_distance()
function as follows:
## Example coordinates
lat1 = 51.5074 ## London
lon1 = -0.1278
lat2 = 48.8566 ## Paris
lon2 = 2.3522
distance = haversine_distance(lat1, lon1, lat2, lon2)
print(f"The distance between London and Paris is {distance:.2f} km.")
This will output:
The distance between London and Paris is 344.00 km.
Handling Exceptions
As mentioned in the previous section, you should handle the ValueError: math domain error
exception that can occur when the input values for latitude and/or longitude are outside the valid range. Here's an example of how to do that:
def haversine_distance(lat1, lon1, lat2, lon2):
try:
## Haversine distance calculation
## ...
except ValueError as e:
if "math domain error" in str(e):
print("Error: Latitude or longitude values are out of range.")
return -1
else:
raise e
By wrapping the Haversine distance calculation in a try-except block, you can catch the ValueError
exception and handle it appropriately, either by printing an error message or raising a more informative exception.