Skip to content

Commit 4c6132f

Browse files
committed
Python script that performs haversine calculations
1 parent a71618f commit 4c6132f

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

haversine_calculation/haversine.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import math
2+
3+
def haversine(lat1, lon1, lat2, lon2):
4+
"""
5+
Calculate the great circle distance in kilometers between two points
6+
on the earth (specified in decimal degrees)
7+
"""
8+
# Convert decimal degrees to radians
9+
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
10+
11+
# Haversine formula
12+
dlat = lat2 - lat1
13+
dlon = lon2 - lon1
14+
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
15+
c = 2 * math.asin(math.sqrt(a))
16+
r = 6371 # Radius of earth in kilometers. Use 3956 for miles.
17+
return c * r
18+
19+
# Example usage
20+
if __name__ == "__main__":
21+
# Coordinates of New York City and London
22+
lat1, lon1 = 40.7128, -74.0060 # New York City
23+
lat2, lon2 = 51.5074, -0.1278 # London
24+
25+
distance = haversine(lat1, lon1, lat2, lon2)
26+
print(f"Distance between New York City and London: {distance:.2f} km")

0 commit comments

Comments
 (0)