Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions haversine_calculation/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# This file makes haversine_calculation a Python package
31 changes: 31 additions & 0 deletions haversine_calculation/haversine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import math


def haversine(lat1, lon1, lat2, lon2):
"""
Calculate the great circle distance in kilometers 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
dlat = lat2 - lat1
dlon = lon2 - lon1
a = (
math.sin(dlat / 2) ** 2
+ math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
)
c = 2 * math.asin(math.sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles.
return c * r


# Example usage
if __name__ == "__main__":
# Coordinates of New York City and London
lat1, lon1 = 40.7128, -74.0060 # New York City
lat2, lon2 = 51.5074, -0.1278 # London

distance = haversine(lat1, lon1, lat2, lon2)
print(f"Distance between New York City and London: {distance:.2f} km")