In calculating distances based on geographical coordinates, utilizing the haversine formula has been widely adopted. However, it assumes a spherical Earth, which can introduce errors. For more accurate calculations, it is necessary to consider the ellipsoidal nature of the planet.
In the code provided, although the haversine formula is correctly implemented, the issue lies in the innacuracy of the assumption. The haversine formula is known to have errors of up to 0.5%.
As a solution, the Python library GeoPy offers a robust distance calculation with the geopty.distance module. This module utilizes the Vincenty distance formula, which employs ellipsoidal models like WGS-84 for greater precision.
To implement it in your code, use the following steps:
For example:
<code class="python">import geopy.distance coords_1 = (52.2296756, 21.0122287) coords_2 = (52.406374, 16.9251681) distance_km = geopy.distance.geodesic(coords_1, coords_2).km print('Distance (in kilometers):', distance_km)</code>
This approach will provide a more accurate distance calculation compared to the haversine formula.
The above is the detailed content of How can I improve the accuracy of geographical distance calculations beyond the haversine formula?. For more information, please follow other related articles on the PHP Chinese website!