from math import radians, sin, cos, sqrt, atan2
def haversine_distance(lat1, lon1, lat2, lon2):
# Convert coordinates from degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# Radius of the Earth in kilometers
earth_radius_km = 6371
# Radius of the Earth in miles
earth_radius_miles = 3959
# Conversion factor from kilometers to feet
km_to_feet = 3280.84
# Calculate the differences in latitude and longitude
dlat = lat2 - lat1
dlon = lon2 - lon1
# Calculate the haversine of the differences
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
# Calculate the central angle of the arc
c = 2 * atan2(sqrt(a), sqrt(1-a))
# Calculate the distance in kilometers, miles, and feet
km = earth_radius_km * c
miles = earth_radius_miles * c
feet = km * km_to_feet
return km, miles, feet
# Get coordinates as user input
lat1 = float(input("Enter latitude of the first point: "))
lon1 = float(input("Enter longitude of the first point: "))
lat2 = float(input("Enter latitude of the second point: "))
lon2 = float(input("Enter longitude of the second point: "))
print("")
# Calculate the distance using the haversine formula
km, miles, feet = haversine_distance(lat1, lon1, lat2, lon2)
# Print the distances
print("The distance betwixt the coordinates is ~")
print("")
print("Kilometers:", km)
print("")
print("Miles:", miles)
print("")
print("Feet:", feet)
# The Haversine formula is used to calculate the distance between two points
# on the surface of a sphere, given their latitude and longitude coordinates.
#It is commonly used in navigation and geographic calculations,
#especially when dealing with small distances on the Earth's surface.
# The formula is derived from the law of haversines,
# which relates the sides and angles of a spherical triangle.
# The Haversine formula is as follows:
# a = sinΒ²(Ξlat/2) + cos(lat1) * cos(lat2) * sinΒ²(Ξlon/2)
# c = 2 * atan2(sqrt(a), sqrt(1-a))
# distance = radius * c
>>
The script output for particular points:
Kilometers: 199.85748332146738
Miles: 124.19334115047705
Feet: 655700.4255804031
-->
Using the haversine formula, I calculated the distance between the coordinates 7.8804Β°N, 98.3923Β°E and 6.73Β°N, 97Β°E is approximately -
Kilometers: 167.7 km
Miles: 104.2 miles
Something is a bit off