|
1 | 1 | import math |
2 | 2 |
|
| 3 | + |
3 | 4 | def haversine(lat1, lon1, lat2, lon2): |
4 | 5 | """ |
5 | | - Calculate the great circle distance in kilometers between two points |
| 6 | + Calculate the great circle distance in kilometers between two points |
6 | 7 | on the earth (specified in decimal degrees) |
7 | 8 | """ |
8 | | - # Convert decimal degrees to radians |
| 9 | + # Convert decimal degrees to radians |
9 | 10 | 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. |
| 11 | + |
| 12 | + # Haversine formula |
| 13 | + dlat = lat2 - lat1 |
| 14 | + dlon = lon2 - lon1 |
| 15 | + a = ( |
| 16 | + math.sin(dlat / 2) ** 2 |
| 17 | + + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 |
| 18 | + ) |
| 19 | + c = 2 * math.asin(math.sqrt(a)) |
| 20 | + r = 6371 # Radius of earth in kilometers. Use 3956 for miles. |
17 | 21 | return c * r |
18 | 22 |
|
| 23 | + |
19 | 24 | # Example usage |
20 | 25 | if __name__ == "__main__": |
21 | 26 | # Coordinates of New York City and London |
22 | 27 | lat1, lon1 = 40.7128, -74.0060 # New York City |
23 | | - lat2, lon2 = 51.5074, -0.1278 # London |
24 | | - |
| 28 | + lat2, lon2 = 51.5074, -0.1278 # London |
| 29 | + |
25 | 30 | distance = haversine(lat1, lon1, lat2, lon2) |
26 | 31 | print(f"Distance between New York City and London: {distance:.2f} km") |
0 commit comments