In this Python guide, we'll delve into the Haversine formula, a powerful tool for determining the distance and bearing between two GPS coordinates.
Problem:
We aim to compute the distance and bearing between two GPS points but encounter a discrepancy in the bearing output, which produces negative values while it should be within the range of 0-360 degrees.
Code:
The provided code utilizes the Haversine formula to calculate both distance and bearing:
from math import radians, cos, sin, asin, sqrt def haversine(lon1, lat1, lon2, lat2): # Convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # Haversine 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)) r = 6371 # Radius of earth in kilometers return c * r
Bearing Calculation:
The issue with the provided code lies in the bearing calculation. To correct it, we need to modify the line:
Bearing = atan2(cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1), sin(lon2-lon1)*cos(lat2))
To:
Bearing = degrees(atan2(sin(lon2-lon1)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon2-lon1)))
This adjustment ensures that the bearing output aligns with the expected range of 0-360 degrees.
Conclusion:
With the bearing calculation fixed, the code now accurately determines the distance and bearing between the provided GPS points. The Haversine formula proves to be a robust tool for geographical calculations, enabling precise measurement of distances on the Earth's surface.
The above is the detailed content of How Can I Correct Negative Bearing Values When Using the Haversine Formula in Python to Calculate Distance and Bearing Between GPS Points?. For more information, please follow other related articles on the PHP Chinese website!