Haversine Formula

Need to find the straight-line distance between two cities using only their latitude and longitude? The haversine formula solves exactly this problem – it computes the shortest distance over the Earth’s surface, treating the planet as a sphere.

Haversine Distance Calculator

Point A
North positive, South negative (−90…90) East positive, West negative (−180…180)
Point B
North positive, South negative (−90…90) East positive, West negative (−180…180)
Units

What Is the Haversine Formula?

The haversine formula calculates the great-circle distance – the shortest path between two points on the surface of a sphere, measured along the surface rather than through it. The term “haversine” is a contraction of “half versed sine”, a trigonometric function defined as:

$$\text{hav}(\theta) = \sin^2\!\left(\frac{\theta}{2}\right) = \frac{1 - \cos\theta}{2}$$

Before electronic calculators existed, navigators and surveyors used haversine tables because the function avoids issues with small-angle rounding that plagued the standard spherical law of cosines. Today the formula remains the standard method for geographic distance calculation in software applications.

The Haversine Formula Explained

Given two points on Earth:

  • Point A: latitude φ₁, longitude λ₁
  • Point B: latitude φ₂, longitude λ₂

the great-circle distance d is found in three steps:

Step 1 – Compute the auxiliary value a:

$$a = \sin^2\!\left(\frac{\Delta\varphi}{2}\right) + \cos\varphi_1 \cdot \cos\varphi_2 \cdot \sin^2\!\left(\frac{\Delta\lambda}{2}\right)$$

where Δφ = φ₂ − φ₁ and Δλ = λ₂ − λ₁ (differences in radians).

Step 2 – Compute the central angle c:

$$c = 2 \cdot \text{atan2}\!\left(\sqrt{a},\;\sqrt{1 - a}\right)$$

Using atan2 instead of arcsin prevents floating-point errors when a rounds to a value slightly outside [0, 1].

Step 3 – Multiply by the Earth’s radius:

$$d = R \cdot c$$

where R ≈ 6,371 km (mean radius of the Earth).

Variable Reference

VariableMeaningUnits
φ₁, φ₂Latitude of points A and Bdegrees → radians
λ₁, λ₂Longitude of points A and Bdegrees → radians
Δφφ₂ − φ₁radians
Δλλ₂ − λ₁radians
aIntermediate haversine valuedimensionless
cCentral angle between pointsradians
RMean Earth radius (6,371 km)km (or miles: 3,958.8)
dGreat-circle distancekm (or miles)

Step-by-Step Example

Calculate the distance from London (51.5074° N, 0.1278° W) to New York (40.7128° N, 74.0060° W).

Convert to radians:

  • φ₁ = 51.5074° → 0.8989 rad
  • λ₁ = −0.1278° → −0.00223 rad
  • φ₂ = 40.7128° → 0.7105 rad
  • λ₂ = −74.0060° → −1.2916 rad

Differences:

  • Δφ = 0.7105 − 0.8989 = −0.1884 rad
  • Δλ = −1.2916 − (−0.00223) = −1.2894 rad

Step 1:

$$a = \sin^2(-0.0942) + \cos(0.8989) \cdot \cos(0.7105) \cdot \sin^2(-0.6447)$$$$a = 0.00884 + 0.6228 \cdot 0.7585 \cdot 0.3629$$$$a = 0.00884 + 0.1717 = 0.1805$$

Step 2:

$$c = 2 \cdot \text{atan2}(\sqrt{0.1805},\;\sqrt{0.8195}) = 2 \cdot 0.4336 = 0.8672 \text{ rad}$$

Step 3:

$$d = 6{,}371 \times 0.8672 \approx 5{,}524 \text{ km}$$

The commonly cited great-circle distance between London and New York is approximately 5,570 km, so the result is within 0.8% – well within the expected margin for the spherical model.

Limitations: Earth Is Not a Perfect Sphere

The haversine formula assumes a perfectly spherical Earth. In reality, Earth is an oblate spheroid – it bulges at the equator and is flattened at the poles. The difference between the equatorial radius (6,378.1 km) and polar radius (6,356.8 km) is about 21.3 km.

This introduces a systematic error of up to 0.5%, which scales with distance:

Route DistanceMaximum Error
100 km~0.5 km
1,000 km~5 km
10,000 km~50 km

For applications demanding sub-meter accuracy (surveying, aviation, precision logistics), ellipsoidal methods like Vincenty’s formulae or Karney’s algorithm are preferred. For most web applications, mapping tools, and “near me” searches, the haversine formula is more than sufficient.

Haversine vs. Other Distance Methods

MethodModelAccuracyComplexity
Euclidean (Pythagorean)Flat planePoor for > 10 kmVery low
Spherical Law of CosinesSphereSimilar to haversine, but numerically unstable for small distancesLow
HaversineSphereGood (≤ 0.5% error)Low–moderate
VincentyEllipsoidExcellent (≤ 0.5 mm)High (iterative)
Karney (GeographicLib)EllipsoidBest availableHigh

The Euclidean method fails because it ignores Earth’s curvature entirely. The spherical law of cosines suffers from floating-point precision loss when two points are very close together. The haversine formula avoids both pitfalls, which is why it became the de facto standard for geographic distance in software.

Practical Applications

The haversine formula powers distance calculations across a wide range of industries:

  • Ride-sharing and delivery apps – Uber, DoorDash, and similar platforms use it to match riders or couriers with nearby drivers in real time.
  • “Near me” search results – search engines and directories filter businesses within a radius from the user’s GPS coordinates.
  • Aviation route planning – flight management systems compute great-circle tracks for fuel planning, though actual flight paths adjust for jet streams.
  • Geofencing – IoT devices and fleet management systems trigger alerts when a vehicle enters or leaves a circular zone.
  • Wildlife tracking – ecologists compute daily travel distances of tagged animals using GPS collar data.
  • Sports and fitness – GPS watches and apps calculate total distance for running, cycling, and hiking routes.

Implementing the Formula in Code

Below is a minimal implementation in Python:

import math

def haversine(lat1, lon1, lat2, lon2):
    R = 6_371  # Earth's mean radius in km

    phi1 = math.radians(lat1)
    phi2 = math.radians(lat2)
    d_phi = math.radians(lat2 - lat1)
    d_lambda = math.radians(lon2 - lon1)

    a = (math.sin(d_phi / 2) ** 2 +
         math.cos(phi1) * math.cos(phi2) *
         math.sin(d_lambda / 2) ** 2)

    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

    return R * c

print(haversine(51.5074, -0.1278, 40.7128, -74.006))

Key implementation notes:

  1. Convert all coordinates to radians before passing them to trigonometric functions – most programming languages’ math.sin and math.cos expect radians.
  2. Use atan2 rather than arcsin for the central angle to avoid domain errors from floating-point rounding.
  3. For miles, replace 6,371 with 3,958.8.

The calculator above performs this computation instantly – enter any two latitude/longitude pairs and get the great-circle distance in kilometers or miles.

The haversine formula provides a spherical approximation; for legal, surveying, or precision engineering purposes, use an ellipsoidal model and verify with official geodetic data.

Frequently Asked Questions

What is the difference between the haversine formula and Vincenty formula?
The haversine formula assumes Earth is a perfect sphere and produces errors up to 0.5%. Vincenty formula models Earth as an ellipsoid (flattened at the poles), achieving accuracy within 0.5 mm – but requires iterative computation and is significantly more complex.
How accurate is the haversine formula for short distances?
For distances under 100 km, the haversine formula is extremely accurate – the spherical approximation introduces negligible error at that scale. It is widely used in mobile apps and web services for nearby-point calculations.
Can the haversine formula be used for planets other than Earth?
Yes. The formula works for any sphere. Simply replace the Earth radius (6,371 km) with the target planet radius – for example, 3,389.5 km for Mars or 6,051.8 km for Venus.
Why not use the Pythagorean theorem to find distance between GPS coordinates?
The Pythagorean theorem assumes a flat plane. On a curved surface like Earth, it underestimates distance and produces large errors over long distances. The haversine formula accounts for curvature by working on a sphere.
What does the word "haversine" mean?
Haversine stands for “half versed sine.” In trigonometry, the versed sine of an angle θ is 1 − cos(θ), and the haversine is half of that: hav(θ) = (1 − cos θ) / 2 = sin²(θ / 2).
At what distance does the haversine formula start to lose accuracy?
The maximum error approaches 0.5% on transcontinental and transoceanic routes (over 10,000 km). For example, a calculated distance of 10,000 km could be off by up to ~50 km compared to an ellipsoidal model.
  1. Distance Calculator – Measure Distance Between Two Points