In the world of navigation, determining the distance and bearing between two GPS points is crucial. The Haversine formula provides a precise way to compute these values using spherical geometry.
To calculate the distance between two GPS points, we need to convert their latitudes and longitudes from decimal degrees to radians. We then apply the formula:
dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon/2) ** 2 c = 2 * asin(sqrt(a)) distance = c * r
where dlon and dlat represent the differences in longitude and latitude, a is an intermediate value, and r is the radius of the Earth (6371 kilometers for kilometers or 3956 miles for miles).
In addition to determining the distance, we can also find the bearing (azimuth) from the first point to the second point using the Haversine formula:
y = sin(dlon) * cos(lat2) x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon) bearing = atan2(y, x)
where dlon is the difference in longitude, lat1 and lat2 are the latitudes of the two points, x and y are intermediate values, and bearing represents the azimuth measured in radians from north clockwise.
Here's a Python implementation of the Haversine formula for calculating distance and bearing:
from math import radians, cos, sin, asin, sqrt def haversine(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6371 return c * r
The above is the detailed content of How Does the Haversine Formula Calculate Distance and Bearing Between GPS Points in Python?. For more information, please follow other related articles on the PHP Chinese website!