Spaces:
Running
Running
| import math | |
| from typing import Union | |
| Number = Union[int, float] | |
| def great_circle_distance_miles(lat1: Number, lon1: Number, lat2: Number, lon2: Number, | |
| radius_miles: float = 3958.8) -> float: | |
| """ | |
| Compute the great-circle distance between two points on the Earth using the haversine formula. | |
| Parameters: | |
| - lat1, lon1: Latitude and longitude of the first point in degrees. | |
| - lat2, lon2: Latitude and longitude of the second point in degrees. | |
| - radius_miles: Radius of the Earth in miles (default 3958.8 miles). | |
| Returns: | |
| - Distance between the two points in miles (float). | |
| Notes: | |
| - Latitude values should be in [-90, 90], longitude values in [-180, 180]. | |
| """ | |
| # convert degrees to radians | |
| phi1 = math.radians(lat1) | |
| phi2 = math.radians(lat2) | |
| dphi = math.radians(lat2 - lat1) | |
| dlambda = math.radians(lon2 - lon1) | |
| # haversine formula | |
| a = math.sin(dphi / 2.0) ** 2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlambda / 2.0) ** 2 | |
| c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) | |
| return radius_miles * c | |
| # Example: | |
| # Distance from New York City (40.7128° N, -74.0060° W) | |
| # to Los Angeles (34.0522° N, -118.2437° W) | |
| if __name__ == "__main__": | |
| ny_lat, ny_lon = 40.7128, -74.0060 | |
| la_lat, la_lon = 34.0522, -118.2437 | |
| print(f"NYC -> LA: {great_circle_distance_miles(ny_lat, ny_lon, la_lat, la_lon):.1f} miles") | |