Blog

Haversine Formula in Python

Haversine Formula

The Haversine formula calculates the distance between two points on the Earth's surface taking into account its spherical shape.

Key Points

  • The Earth is approximately spherical.
  • The formula computes the great-circle distance — the shortest path between two points on a sphere.
  • Latitude and longitude coordinates are used.

Formulas

R = 6371 km (Earth's radius)
Δlat = lat2 - lat1
Δlon = lon2 - lon1
a = sin²(Δlat/2) + cos(lat1) * cos(lat2) * sin²(Δlon/2)
c = 2 * arctan2(√a, √(1-a))
d = R * c
    

Python Example

import math

def haversine(lat1, lon1, lat2, lon2):
    R = 6371  # Earth's radius in kilometers
    # Convert degrees to radians
    lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])

    dlat = lat2 - lat1
    dlon = lon2 - lon1

    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

    distance = R * c
    return distance


# Example usage:
berlin = (52.52, 13.4)
paris = (48.85, 2.35)

dist = haversine(berlin[0], berlin[1], paris[0], paris[1])
print(f"Distance between Berlin and Paris: {dist:.2f} km")

# Distance between Berlin and Paris: 877.68 km
Read more >>

Tags list

    Apps Script      Arrays Java Script      asynchronous code      asyncio      coroutine      Django      Dropdown List      Drop Shipping      Exceptions      GitHub      Google API      Google Apps Script      Google Docs      Google Drive      Google Sheets      Haversine      multiprocessing      Parsing      Python      regex      Scraping      ssh      Test Driven Development (TDD)      threading      website monitoring      zip