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.
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
| Variable | Meaning | Units |
|---|---|---|
| φ₁, φ₂ | Latitude of points A and B | degrees → radians |
| λ₁, λ₂ | Longitude of points A and B | degrees → radians |
| Δφ | φ₂ − φ₁ | radians |
| Δλ | λ₂ − λ₁ | radians |
| a | Intermediate haversine value | dimensionless |
| c | Central angle between points | radians |
| R | Mean Earth radius (6,371 km) | km (or miles: 3,958.8) |
| d | Great-circle distance | km (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 Distance | Maximum 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
| Method | Model | Accuracy | Complexity |
|---|---|---|---|
| Euclidean (Pythagorean) | Flat plane | Poor for > 10 km | Very low |
| Spherical Law of Cosines | Sphere | Similar to haversine, but numerically unstable for small distances | Low |
| Haversine | Sphere | Good (≤ 0.5% error) | Low–moderate |
| Vincenty | Ellipsoid | Excellent (≤ 0.5 mm) | High (iterative) |
| Karney (GeographicLib) | Ellipsoid | Best available | High |
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:
- Convert all coordinates to radians before passing them to trigonometric functions – most programming languages’
math.sinandmath.cosexpect radians. - Use
atan2rather thanarcsinfor the central angle to avoid domain errors from floating-point rounding. - 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.