Haversine Formula in Python: GPS Distance and Bearing

Almost every location-aware product eventually needs the same two numbers: how far apart two GPS points are, and which compass direction one lies from the other. Delivery apps estimate arrival times from distance, hiking apps show the heading to the next waypoint, and fleet dashboards alert when a vehicle drifts off course. The haversine formula gives you the distance quickly and accurately enough for the vast majority of these jobs, and a companion atan2 expression gives you the bearing.

This guide explains the geometry behind both calculations and turns it into Python code you can drop into a project. You will learn how to convert the raw angle into a proper 0–360° compass bearing, how to handle edge cases such as identical points and antimeridian crossings, which Earth radius to pick for kilometers, miles, or nautical miles, when the spherical model starts to hurt, and which maintained libraries (geopy, geographiclib, pyproj) to reach for when you need ellipsoidal accuracy.

Table of Contents#

  1. GPS Coordinates and What Distance Means on Earth
  2. How the Haversine Formula Works
  3. Choosing an Earth Radius for Your Units
  4. Bearing (Azimuth) Between Two GPS Points
  5. Normalizing Bearings to 0–360 Degrees
  6. Pure-Python Implementation (Standard Library Only)
  7. Worked Example: Distance and Bearing from Berlin to Paris
  8. Spherical vs Ellipsoidal Accuracy
  9. Python Libraries for Geo Distance and Bearing
  10. Batch Calculations with NumPy
  11. Real-World Use Cases
  12. Common Pitfalls and Best Practices
  13. Testing Your Implementation
  14. Conclusion
  15. References

GPS Coordinates and What Distance Means on Earth#

A GPS fix is a pair of angles on the reference ellipsoid used by satellite navigation (WGS 84):

  • Latitude (lat, φ) — angle north or south of the equator, from −90° at the South Pole to +90° at the North Pole.
  • Longitude (lon, λ) — angle east or west of the Prime Meridian, from −180° to +180°. West and south values are negative, so Rio de Janeiro is (−22.9068, −43.1729) in decimal degrees.

Two modeling decisions follow, and both matter for correctness.

Earth is not a sphere. WGS 84 defines an oblate ellipsoid with equatorial radius 6 378 137 m, polar radius about 6 356 752.3 m, and flattening 1/298.257223563. Treating it as a sphere is a deliberate approximation — the haversine formula does exactly that — and the resulting distance error is typically a few tenths of a percent. Section Spherical vs Ellipsoidal Accuracy quantifies it and shows when to switch models.

"Distance" means surface distance along a shortest path. On a sphere, that path is an arc of a great circle (an "as-the-crow-flies" ground distance that ignores terrain and altitude). On an ellipsoid it is a geodesic. The two are close but not identical, which is why two reputable libraries can disagree in the third decimal place.

Finally, watch coordinate order. Most Python geo libraries take (lat, lon), but GeoJSON, PostGIS, and pyproj work with (lon, lat). Silent swaps produce plausible-looking nonsense — a point in the Indian Ocean instead of off the coast of Norway — so pin the convention down in your API.

How the Haversine Formula Works#

The haversine formula computes the great-circle distance between two points from their latitudes and longitudes. The word haversine is a 19th-century contraction of "half versed sine": for an angle θ,

hav(θ) = sin²(θ/2) = (1 − cos θ) / 2

Given points 1 and 2 with latitudes φ1, φ2 and longitudes λ1, λ2 expressed in radians, the central angle between them follows from

a = hav(Δφ) + cos φ1 · cos φ2 · hav(Δλ)
  = sin²(Δφ/2) + cos φ1 · cos φ2 · sin²(Δλ/2)

c = 2 · atan2(√a, √(1 − a))

d = R · c

where Δφ = φ2 − φ1, Δλ = λ2 − λ1, R is the Earth radius in your chosen unit, c is the central angle in radians, and d is the resulting distance. The term a is the squared half-chord length between the points on the unit sphere.

Why prefer this over the spherical law of cosines (d = R · acos(sin φ1 · sin φ2 + cos φ1 · cos φ2 · cos Δλ)), which is mathematically equivalent? Numerical conditioning. acos loses precision badly for small angles, while the haversine form stays numerically well-conditioned even for tiny separations — a property that made it a favorite of 1980s microcomputer navigation code and keeps it useful today when you are measuring distances of a few meters between GPS samples. For very short spans (a couple of meters or less) an equirectangular approximation is cheaper still, but haversine is the sweet spot for general use.

One practical note: atan2(√a, √(1 − a)) is preferred over asin(√a) because it avoids a domain error when rounding pushes a slightly above 1 — still clamp a to 1.0 before the square roots, since sqrt of a negative number raises in Python.

Choosing an Earth Radius for Your Units#

Because d = R · c, the unit of the answer is entirely determined by the radius you plug in. Common choices:

Unit of resultRadius RNotes
kilometers6371.0088IUGG mean radius (2a + b)/3 for WGS 84; the nominal 6371 km is fine for most work
miles3958.766371.0088 km ÷ 1.609344 km/mi
meters6 371 008.8just scale the kilometer value
nautical miles3440.076371.0088 km ÷ 1.852 km/nmi

geopy uses EARTH_RADIUS = 6371.009 km for its great-circle calculations, scikit-learn's example uses 6 371 000 m, and older snippets often hard-code 6371 or 3959. Any of these is consistent as long as one radius definition flows through your codebase; mixing them between call sites is how "the same" distance comes out two different ways. Put the constant in one module and convert only at the edges.

Bearing (Azimuth) Between Two GPS Points#

The bearing (or forward azimuth) is the angle you would read on a compass at point 1 to travel along the shortest path toward point 2: measured clockwise from true north, so north is 0°, east 90°, south 180°, and west 270°. On a sphere it comes from the spherical trigonometry of the same triangle that gives haversine its central angle:

y = sin(Δλ) · cos φ2
x = cos φ1 · sin φ2 − sin φ1 · cos φ2 · cos(Δλ)

θ = atan2(y, x)

Again, φ and λ must be in radians; Δλ = λ2 − λ1. Python's math.atan2(y, x) returns the angle in radians in the range [−π, +π], i.e. −180° to +180° after conversion with math.degrees.

Initial bearing is not a constant heading#

A great-circle route has a different heading at every moment. The formula above is the initial bearing (forward azimuth) — the heading you start with. The final bearing is the direction of travel on arrival, and over long east–west routes the two can differ dramatically. A flight from Berlin (52.52° N, 13.41° E) toward Tokyo (35.68° N, 139.65° E) starts out at about 41.7° (northeast) but arrives heading about 150.1° (south-southeast), because the great circle arcs up over Siberia and back down. Even a short hop between two points at the same latitude bows poleward: Berlin-to-Paris-style legs show a couple of degrees of drift, and two points 1° of longitude apart at 40° N start at 270.3° and finish at 269.7°.

The final bearing is cheap to obtain: compute the initial bearing from the end point back to the start point and reverse it with (θ + 180) % 360.

Normalizing Bearings to 0–360 Degrees#

atan2 hands back −180° to +180°, but compasses, navigation APIs, and most UIs expect 0° ≤ θ < 360°. Negative results are simply the same direction counted counterclockwise from north (westward): −45° and 315° both mean northwest. The fix is one modulo operation after converting to degrees:

bearing = (θ_degrees + 360) % 360
atan2 output (°)Compass bearing (°)Direction
51.251.2northeast
−45.0315.0northwest
−90.0270.0west
−180.0180.0south
180.0180.0south

Two details of this expression are worth knowing:

  1. Adding 360 first makes the dividend positive, so Python's % (which returns a result with the sign of the divisor) lands in [0, 360) for every input angle that atan2 can produce. It also works for already-positive angles: 180° stays 180°, not 540°.
  2. Applying it is not optional in navigation code. A bearing of −83° rendered raw can send a turn-by-turn UI haywire, while 277° is unambiguous.

If you need quadrant labels, round the normalized value into the nearest 45° sector: ["N", "NE", "E", "SE", "S", "SW", "W", "NW"][int((bearing + 22.5) // 45) % 8].

Pure-Python Implementation (Standard Library Only)#

The complete calculation needs nothing beyond the math module. The implementation below validates coordinates, keeps unit selection explicit, exposes both bearings, and includes the inverse ("direct") problem — projecting a destination point from a start point, bearing, and distance — which is the natural companion for simulating movement or drawing radius rings.

"""Great-circle distance and compass bearings between GPS points."""
 
from __future__ import annotations
 
import math
from dataclasses import dataclass
 
# IUGG mean radius of WGS 84: (2a + b) / 3
EARTH_RADIUS_KM = 6371.0088
 
UNIT_RADII_KM = {
    "km": EARTH_RADIUS_KM,
    "miles": 3958.76,
    "nautical_miles": 3440.07,
    "meters": EARTH_RADIUS_KM * 1000.0,
}
 
 
@dataclass(frozen=True)
class GeoPoint:
    """A geographic position on the WGS 84 datum, in decimal degrees."""
 
    lat: float
    lon: float
 
    def __post_init__(self) -> None:
        if not -90.0 <= self.lat <= 90.0:
            raise ValueError(f"latitude {self.lat} outside [-90, 90]")
        if not -180.0 <= self.lon <= 180.0:
            raise ValueError(f"longitude {self.lon} outside [-180, 180]")
 
 
def normalize_bearing(degrees: float) -> float:
    """Wrap any angle to the compass range [0, 360)."""
    return (degrees + 360.0) % 360.0
 
 
def great_circle_distance(
    a: GeoPoint,
    b: GeoPoint,
    unit: str = "km",
    radius: float | None = None,
) -> float:
    """Haversine distance between two points, in `unit` (or scaled by `radius`)."""
    r = UNIT_RADII_KM[unit] if radius is None else radius
    phi1, phi2 = math.radians(a.lat), math.radians(b.lat)
    d_phi = math.radians(b.lat - a.lat)
    d_lambda = math.radians(b.lon - a.lon)
 
    a_term = (
        math.sin(d_phi / 2.0) ** 2
        + math.cos(phi1) * math.cos(phi2) * math.sin(d_lambda / 2.0) ** 2
    )
    a_term = min(1.0, a_term)  # guard against float drift past 1.0
    central = 2.0 * math.atan2(math.sqrt(a_term), math.sqrt(1.0 - a_term))
    return r * central
 
 
def initial_bearing(a: GeoPoint, b: GeoPoint) -> float:
    """Forward azimuth from `a` to `b`, normalized to [0, 360) degrees."""
    phi1, phi2 = math.radians(a.lat), math.radians(b.lat)
    d_lambda = math.radians(b.lon - a.lon)
 
    y = math.sin(d_lambda) * math.cos(phi2)
    x = math.cos(phi1) * math.sin(phi2) - math.sin(phi1) * math.cos(phi2) * math.cos(
        d_lambda
    )
    return normalize_bearing(math.degrees(math.atan2(y, x)))
 
 
def final_bearing(a: GeoPoint, b: GeoPoint) -> float:
    """Direction of travel on arrival at `b` along the great circle from `a`."""
    return normalize_bearing(initial_bearing(b, a) + 180.0)
 
 
def destination_point(
    start: GeoPoint,
    bearing_deg: float,
    distance: float,
    unit: str = "km",
    radius: float | None = None,
) -> GeoPoint:
    """Point reached by traveling `distance` from `start` on `bearing_deg`."""
    r = UNIT_RADII_KM[unit] if radius is None else radius
    phi1 = math.radians(start.lat)
    lam1 = math.radians(start.lon)
    theta = math.radians(bearing_deg)
    delta = distance / r
 
    phi2 = math.asin(
        math.sin(phi1) * math.cos(delta)
        + math.cos(phi1) * math.sin(delta) * math.cos(theta)
    )
    lam2 = lam1 + math.atan2(
        math.sin(theta) * math.sin(delta) * math.cos(phi1),
        math.cos(delta) - math.sin(phi1) * math.sin(phi2),
    )
    return GeoPoint(math.degrees(phi2), (math.degrees(lam2) + 540.0) % 360.0 - 180.0)
 
 
def compass_point(bearing_deg: float) -> str:
    """Nearest of the eight cardinal/intercardinal labels."""
    labels = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
    return labels[int((normalize_bearing(bearing_deg) + 22.5) // 45) % 8]

Design points that pay off in production:

  • GeoPoint is immutable and range-checked, so out-of-bounds values fail at construction instead of returning a silently wrong number hundreds of lines later.
  • min(1.0, a_term) keeps sqrt(1 − a) real even when floating-point error nudges a fractionally above 1 (antipodal points already push a to exactly 1).
  • Units are a first-class argument; passing radius overrides the built-in table if your project pins a different constant.
  • Bearings are normalized in exactly one place, normalize_bearing, so the 0–360 rule cannot be applied inconsistently.

Worked Example: Distance and Bearing from Berlin to Paris#

berlin = GeoPoint(52.5200, 13.4050)
paris = GeoPoint(48.8566, 2.3522)
 
dist = great_circle_distance(berlin, paris)
b0 = initial_bearing(berlin, paris)
b1 = final_bearing(berlin, paris)
 
print(f"distance : {dist:.2f} km")
print(f"initial  : {b0:.2f}° ({compass_point(b0)})")
print(f"final    : {b1:.2f}° ({compass_point(b1)})")
 
arrival = destination_point(berlin, b0, dist)
print(f"arrival  : {arrival.lat:.4f}, {arrival.lon:.4f}")

Output:

distance : 877.46 km
initial  : 246.74° (SW)
final    : 238.18° (SW)
arrival  : 48.8566, 2.3522

The projected arrival reproduces the Paris input to floating-point precision — the definitive round-trip check that the direct and inverse problems are mutually consistent. Compute with the rounded display values instead (246.74° and 877.46 km) and the arrival lands roughly 50 m from the target, which is why rounding belongs in the view layer, not in intermediate calculations.

For an independent cross-check, compute the same leg with an ellipsoidal geodesic solver:

from geopy.distance import geodesic, great_circle
 
print(great_circle((52.5200, 13.4050), (48.8566, 2.3522)).km)  # 877.465
print(geodesic((52.5200, 13.4050), (48.8566, 2.3522)).km)      # 879.699

The spherical haversine result (877.46 km) and the WGS 84 geodesic result (879.70 km) differ by about 0.25% — the expected order of magnitude for the spherical approximation over 900 km.

Edge cases to expect#

CaseDistanceInitial bearingComment
Identical points0.00.0 (convention)Direction is mathematically undefined; atan2(0, 0) returns 0.0 in Python. final_bearing reports 180° for identical points — treat both as undefined in application logic
1° due north along a meridian111.20 km0.0°On the ellipsoid the same span is 110.57 km
1° due east along the equator111.20 km90.0°Ellipsoidal value is 111.32 km
Crossing the antimeridian (Nadi → Apia)1235.29 km70.75°Works without special-casing — see Common Pitfalls

Spherical vs Ellipsoidal Accuracy#

The haversine formula assumes a perfect sphere, and Earth is about a third of a percent off that — so is the distance it returns. Two failure modes show up in practice:

  1. Direction-dependent bias. Along a meridian, one degree of latitude is shorter on the WGS 84 ellipsoid (110.57 km) than on a sphere of mean radius (111.20 km), a +0.56% haversine overshoot. Along the equator the same test undershoots by about 0.11%. Typical route-length errors across mixed directions cluster around 0.2–0.5%, which is why geopy documents "an error of up to about 0.5%" for its spherical mode.
  2. Absolute error scales with distance. A 0.3% bias is 3 m on a 1 km delivery leg and 30 km on a trans-Pacific route. Fine for "restaurants within 2 km", unacceptable for cadastral surveying or geodesic control networks.

When the budget is tighter, move from spherical formulas to ellipsoidal geodesics on WGS 84:

  • Vincenty's formulae (1975) are the classic iterative solution, accurate to within 0.5 mm on the ellipsoid. Their known weakness: the inverse problem sometimes fails to converge for nearly antipodal points.
  • Karney's algorithm (2013) is the modern replacement used by GeographicLib, geopy, and pyproj. geopy describes its geodesic method as "accurate to round-off and always converges", which is why it is the default behind geopy.distance.distance.

You do not have to choose one globally. A common pattern is haversine for cheap pre-filtering ("candidate points within ~5 km") and a geodesic solver for the final ranking or for billing-grade numbers. Just label which model produced which value — mixing the two in the same table is a classic source of bug reports.

Python Libraries for Geo Distance and Bearing#

Rolling your own is excellent for understanding and for dependency-free hot paths, but in 2026 the maintained libraries are more robust for production:

LibraryWhat you getUnits / conventionsNotes
geopygreat_circle, geodesic, distance(lat, lon) tuples; result object with .km, .miles, .m, .nautical attributesVersion 2.5.0 (2026). distance and geodesic use Karney's algorithm on WGS 84 by default; great_circle is the haversine-style spherical option
geographiclibGeodesic.WGS84.Inverse / Directlat, lon in degrees; distances in metersInverse returns the forward azimuth at both ends (azi1, azi2) and the distance s12 in a single call — ideal when you need bearing and distance together
pyprojpyproj.Geod(ellps="WGS84") with .inv and .fwdlon first: g.inv(lon1, lat1, lon2, lat2); distances in metersVectorized over NumPy arrays; .inv returns forward azimuth, back azimuth, and distance. Part of the PROJ ecosystem
scikit-learnhaversine_distances(X, Y)Points are (lat, lon) in radians; output is angular distanceMultiply the matrix by an Earth radius to get physical units — forgetting this is the most common misuse
math (standard library)everything above, by handyour choiceNo dependencies; you own the edge cases

Bearing with geographiclib:

from geographiclib.geodesic import Geodesic
 
inv = Geodesic.WGS84.Inverse(52.5200, 13.4050, 48.8566, 2.3522)
azi1 = (inv["azi1"] + 360.0) % 360.0
azi2 = (inv["azi2"] + 360.0) % 360.0
print(f"{azi1:.2f}° -> {azi2:.2f}°, {inv['s12'] / 1000:.2f} km")
# 246.81° -> 238.24°, 879.70 km

Inverse solves distance and both azimuths in one call, but its azimuths come back in [−180, 180] (this example returns −113.19° and −121.76° before normalization), so run them through the same (θ + 360) % 360 wrapper as your own formulas.

Bearing and distance in one pyproj call (note the argument order):

from pyproj import Geod
 
g = Geod(ellps="WGS84")
az12, az21, dist_m = g.inv(13.4050, 52.5200, 2.3522, 48.8566)
print(f"initial {(az12 + 360) % 360:.2f}°, distance {dist_m / 1000:.2f} km")
# initial 246.81°, distance 879.70 km

Both azimuths from Geod.inv are conventionally returned in (−180, 180]; run them through the same (θ + 360) % 360 normalization before display (the Berlin–Paris leg comes back as −113.19°, i.e. 246.81°).

Batch Calculations with NumPy#

Real datasets are tables of thousands of coordinates. Python loops over the scalar function are fine up to a few thousand pairs; beyond that, express the haversine formula with NumPy ufuncs so the whole array is processed in C:

import numpy as np
 
EARTH_RADIUS_KM = 6371.0088
 
def haversine_km(lat1, lon1, lat2, lon2):
    """Vectorized haversine distance; scalars or arrays in, float/array out."""
    lat1, lon1, lat2, lon2 = np.radians([lat1, lon1, lat2, lon2])
    d_lat = lat2 - lat1
    d_lon = lon2 - lon1
    a = np.sin(d_lat / 2.0) ** 2 + np.cos(lat1) * np.cos(lat2) * np.sin(d_lon / 2.0) ** 2
    return EARTH_RADIUS_KM * 2.0 * np.arctan2(np.sqrt(a), np.sqrt(1.0 - a))
 
lats_from = np.array([52.5200, 0.0])
lons_from = np.array([13.4050, 0.0])
lats_to   = np.array([48.8566, 1.0])
lons_to   = np.array([2.3522, 0.0])
 
print(haversine_km(lats_from, lons_from, lats_to, lons_to))
# [877.46453792 111.19508023]

The same idea applies to a full distance matrix: broadcasting lat1[:, None] against lat2[None, :] yields an N×M matrix of kilometers in one pass, which is exactly how proximity search over a large store list is usually implemented.

Real-World Use Cases#

Proximity filtering ("stores within 500 km"). Compute distances to a fixed anchor and filter — simple, and fast enough with NumPy:

anchor = GeoPoint(52.5200, 13.4050)  # Berlin
stores = {
    "Hamburg": GeoPoint(53.5511, 9.9937),
    "Munich": GeoPoint(48.1351, 11.5820),
    "Warsaw": GeoPoint(52.2297, 21.0122),
    "Prague": GeoPoint(50.0755, 14.4378),
    "Paris": GeoPoint(48.8566, 2.3522),
}
nearby = [
    name
    for name, point in stores.items()
    if great_circle_distance(anchor, point) <= 500.0
]
print(nearby)  # ['Hamburg', 'Prague']  (255.3 km, 281.1 km; Munich is 504.4 km)

For very large candidate sets, pre-filter with a cheap latitude/longitude bounding box (±0.5° of latitude per 55 km, longitude scaled by cos(lat)) and run haversine only on the survivors.

Geofencing. A geofence is usually a radius check: flag a delivery vehicle as "arrived" when great_circle_distance(geofence_center, vehicle) < 250 meters. Because GPS noise is on the order of 5–15 m outdoors, pick a hysteresis band (enter at 250 m, exit at 300 m) instead of a single threshold.

Route and ETA estimation. Distance ÷ average speed is the baseline ETA; the initial bearing feeds map orientation and turn instructions, while the final bearing detects the approach direction ("arriving from the northeast").

Fleet heading checks. Comparing the bearing between two consecutive fixes with the vehicle's reported course over ground quickly exposes GPS jumps: a 100 m sample that implies a 90° heading change at 30 km/h is a bad fix, not a U-turn.

Sorting and ranking. "Nearest technician" is a sort by haversine distance; tie-break with the geodesic value if dispatch billing depends on the difference.

Common Pitfalls and Best Practices#

  1. Degrees fed to trig functions. math.sin expects radians. Convert once with math.radians (and back with math.degrees); in NumPy use np.radians. This is the single most common source of absurd distances.
  2. Latitude/longitude swaps. GeoPoint(13.4050, 52.5200) silently reverses Berlin into the Arabian Sea. Validate ranges in a constructor, and remember pyproj's (lon, lat) order versus geopy's (lat, lon).
  3. Radius/unit mismatches. A distance computed with R = 6371 is kilometers; the same call with R = 6371000 is meters. One constant, one place.
  4. Un-normalized bearings. Anything user-facing should show [0, 360). Keep normalize_bearing between atan2 and the world.
  5. Initial vs final bearing confusion. They differ on long legs (Berlin–Tokyo: 41.7° vs 150.1°). Document which one your API returns.
  6. Antimeridian anxiety. For the haversine and azimuth formulas you do not need to wrap Δλ: sine and cosine are 360°-periodic, so Nadi (177.4° E) → Apia (171.8° W) returns the correct 1235 km whether Δλ is coded as −349.2° or +10.8°. Wrapping does matter for bounding boxes, equirectangular approximations, and rhumb lines, so normalize there — (lon + 540) % 360 − 180.
  7. Identical points. Distance is 0, bearing is undefined (atan2(0, 0) → 0.0), and final_bearing reports 180° as an artifact of the reverse-and-add-180 trick. Handle the branch explicitly in navigation code.
  8. Assuming a constant heading. Following an initial bearing along a great circle does take you to the destination, but the compass reading keeps changing. Convert to a rhumb line only when a constant heading is genuinely required.
  9. Ignoring altitude and terrain. These formulas return distance along the reference surface. Airline "great-circle distance" is not flight distance at altitude, and mountain routes are longer on the ground.
  10. Trusting a to stay ≤ 1. Clamp before sqrt, or antipodal inputs may raise ValueError: math domain error.
  11. Comparing numbers from different models. A spherical and an ellipsoidal distance for the same pair will differ by a few tenths of a percent. That is expected — not a bug in your port.
  12. Micro-optimizing the scalar form. Factoring out shared trig terms rarely pays in CPython; if the hot loop is too slow, switch to NumPy rather than hand-tuning.

Testing Your Implementation#

Treat geopy or geographiclib as the oracle and assert your haversine results within a tolerance of a few tenths of a percent:

import pytest
from geographiclib.geodesic import Geodesic
 
def test_matches_geodesic_within_05_percent():
    a, b = GeoPoint(52.5200, 13.4050), GeoPoint(48.8566, 2.3522)
    got = great_circle_distance(a, b)
    expected = Geodesic.WGS84.Inverse(a.lat, a.lon, b.lat, b.lon)["s12"] / 1000.0
    assert got == pytest.approx(expected, rel=0.005)
 
def test_bearings_are_normalized():
    for pair in [(0.0, 0.0, 10.0, -170.0), (10.0, -20.0, -10.0, 20.0)]:
        b0 = initial_bearing(GeoPoint(pair[0], pair[1]), GeoPoint(pair[2], pair[3]))
        assert 0.0 <= b0 < 360.0
 
def test_zero_distance():
    p = GeoPoint(10.0, 20.0)
    assert great_circle_distance(p, p) == 0.0

A solid checklist for any port of these formulas:

  • cardinal directions: moving 1° east along the equator yields bearing 90.0°; 1° north along a meridian yields 0.0°;
  • antimeridian pair (e.g. 177.4° E → 171.8° W) equals the same pair with longitudes wrapped;
  • nearly antipodal points return ≈ half the circumference (πR ≈ 20 015 km with R = 6371 km) without a domain error;
  • a destination projection followed by the inverse calculation recovers the original bearing and distance;
  • all four quadrants of normalize_bearing, including exactly −180° and 180°.

Conclusion#

The haversine formula remains the right first tool for distance between two GPS points in Python: the math is short, the standard-library implementation is numerically stable even at meter scale, and a scalar call costs on the order of a microsecond or less. Pair it with the atan2 azimuth formula and a single (θ + 360) % 360 normalization step and you have complete, reliable distance-and-bearing support for navigation displays, proximity search, and geofencing.

The takeaways worth carrying into production code:

  • Convert to radians before any trigonometry, and keep one Earth-radius constant per unit system (6371.0088 km is the IUGG mean radius; scale it for miles or nautical miles).
  • Normalize every bearing to [0, 360), and know whether your API reports the initial bearing, the final bearing, or both — they diverge on long routes.
  • Expect spherical error on the order of 0.2–0.5%; when that budget is too tight, use geopy, geographiclib, or pyproj for WGS 84 geodesics built on Karney's 2013 algorithm, which converges even where Vincenty's method fails.
  • Handle identical points, clamp the haversine a term, and remember that trig periodicity makes the antimeridian a non-issue for the formulas themselves.
  • For large batches, vectorize with NumPy instead of looping.

Do those five things and the problem this article set out to solve — haversine distance and bearing between two GPS points in Python — is solved for good.

References#