Ask Any Question Here

Our experts will answer any of your questions about ERP, business automation, software development, setup and customization, system architecture and much more

Ask Any Question Here

Our experts will answer any of your questions about ERP, business automation, software development, setup and customization, system architecture and much more

How to Evaluate Distance Correctly Between Two Points in Python

Question:

My code is not working.

I want to calculate the distance between two points on the Earth’s surface based on their latitude and longitude using the haversine formula.

The haversine formula is a method to find the great-circle distance between two points on a sphere given their longitudes and latitudes.

from math import sin, cos, sqrt, atan2

earth_radius = 6373.0

latitude1 = 43.4395755
longitude1 = 23.2267012
latitude2 = 47.0566784
longitude2 = 14.5931164


delta_longitude = longitude2 - longitude1
delta_latitude = latitude2 - latitude1
angle_a = (sin(delta_latitude / 2))**2 + cos(latitude1) * cos(latitude2) * (sin(delta_longitude / 2))**2
angular_distance = 2 * atan2(sqrt(angle_a), sqrt(1 - angle_a))
distance = earth_radius * angular_distance

print("Result:", distance)

#Output:
#Result: 6176.896859755734


It returns the distance 6176.896859755734, but not 786 km. Why?


Answer:

Just as a note, if you just need a quick and easy way of finding the distance between two points, I strongly recommend not implementing Haversine.

You have the option to transform the numbers manually into radians, or utilize the radians functionality from the math module:


from math import sin, cos, sqrt, atan2, radians

# Approximate radius of earth in km
earth_radius_km = 6373.0
latitude1_rad = radians(43.4395755)
longitude1_rad = radians(23.2267012)
latitude2_rad = radians(47.0566784)
longitude2_rad = radians(14.5931164)

delta_longitude_rad = longitude2_rad - longitude1_rad
delta_latitude_rad = latitude2_rad - latitude1_rad

angle_a = sin(delta_latitude_rad / 2)**2 + cos(latitude1_rad) * cos(latitude2_rad) * sin(delta_longitude_rad / 2)**2
angular_distance = 2 * atan2(sqrt(angle_a), sqrt(1 - angle_a))

distance_km = earth_radius_km * angular_distance


print("Result:", distance_km)
#Output:
#Result: 786.0811347907835

Here we converted latitude and longitude to radians using the radians function. The haversine formula requires angles in radians for accurate calculations.

The distance is now returning the correct value of 786 km.


Ask Your Question Right Here

We're Here To Help!