← Math
Math

Numerical stability and conditioning

Why does a waiting courier’s trip grow, shrink or turn into NaN?

Separate arithmetic error from sensitivity in the problem and uncertainty in its inputs.

Outcome

Tell an unstable formula from a sensitive problem, rewrite the distance so short segments survive, and decide arrival only when the fix’s accuracy allows it.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Cancellation
Subtracting two nearly equal floating-point numbers; the leading digits cancel, so earlier rounding errors can dominate the small remaining difference.
Stable algorithm
A way of computing a result whose rounding errors stay about as small as the inputs’ own.
Condition
How much a problem’s answer moves when its input moves a little, whatever algorithm computes it.
Great-circle distance
The shortest distance between two points on a sphere, along its surface.
Haversine formula
A form of the great-circle distance built from sin² of half the differences, which stays accurate for nearby points.
Horizontal accuracy
The radius, in metres, within which a phone’s location fix is likely to be; browsers report it as coords.accuracy.

Why this matters

Floating-point arithmetic is accurate to about 16 significant digits, which is plenty for a distance in metres. Formulas still go wrong when they subtract two nearly equal numbers, because the digits that would tell them apart are gone. Location code meets this every time a phone stands still.

This lesson assumes floating point and rounding, and square roots.

What stability and conditioning describe

Conditioning describes how the exact answer changes when the inputs change. Stability describes how a calculation handles the rounding in its intermediate values. Two formulas can be equal on paper and preserve very different amounts of information when evaluated in floating point.

Absolute error measures a difference in the answer’s units; relative error compares that difference with the answer’s size. A small distance can have a small absolute error and a large relative error. A stable calculation still uses the supplied measurements and geometric model, so its numerical precision cannot establish the accuracy of a GPS fix.

01Short distances on a flat map

Short distances on a flat map

A delivery app adds up the distance between a courier’s GPS fixes, one per second, to show the trip length and to decide when the courier has arrived. While the courier waits at a door, successive reported fixes differ by centimetres, and the trip length jumps around or becomes NaN. The formula is correct on paper; the way it is computed is not.

For the courier’s local Oslo map, a flat approximation is sufficient. North is the latitude difference times the radius; east is the longitude difference times the radius times cos(latitude), because meridians meet at the poles. In Oslo a degree of longitude is about half a degree of latitude, and leaving out the cosine makes a 2.1 km trip read 3.4 km.

Flat map against the great circle
TripFlat mapGreat circle
Across Oslo2,126.56 m2,126.56 m
Helsinki to Stockholm396,019.68 m395,819.56 m

02Rewrite, don’t subtract

Rewrite, don’t subtract

Predict the two lines this program prints for two fixes 0.27 m apart.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const R = 6_371_000; // metres
const rad = (degrees: number) => (degrees * Math.PI) / 180;
const [lat1, lon1, lat2, lon2] = [48.85837, 2.294481, 48.858372, 2.294483]; // two GPS fixes of a waiting courier

const c =
  Math.sin(rad(lat1)) * Math.sin(rad(lat2)) +
  Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.cos(rad(lon2 - lon1));

console.log((R * Math.acos(c)).toFixed(3)); // law of cosines
const h =
  Math.sin(rad(lat2 - lat1) / 2) ** 2 +
  Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(rad(lon2 - lon1) / 2) ** 2;

console.log((2 * R * Math.asin(Math.sqrt(h))).toFixed(3)); // haversine
What are the two printed distances on this checked toolchain?

Let φ be latitude and λ longitude, both in radians. Compute h = sin²(Δφ/2) + cos(φ₁)cos(φ₂)sin²(Δλ/2), then d = 2R asin(√h). This is the same spherical geometry because cos(d/R) = 1 − 2h. The useful change is computing the small positive h directly, instead of recovering it from a rounded number near 1.

A teammate clamps the acos argument to at most 1. Is the trip length fixed?

03Problem or algorithm?

Problem or algorithm?

Moving either point by a centimetre changes the true spherical distance by at most a centimetre. This is good absolute conditioning. Relative error is a different question: a centimetre is a large fraction of a centimetre-long segment. The law of cosines loses the answer anyway, which makes it an unstable way to compute these short segments. More printed digits cannot help: the digits were lost before printing. Writing sin² as (1 − cos)/2 looks like haversine but brings the subtraction back.

04Accuracy decides

Accuracy decides

A phone reports an estimated horizontal accuracy with each fix. For this worked decision model, assume the true position lies within that radius; the browser estimate itself is not a guaranteed physical bound. A fix 28.35 m from the drop-off with 25 m accuracy puts the courier anywhere from 3.35 m to 53.35 m away. Against a 40 m arrival radius, that range is partly inside and partly outside.

Fix 28.35 m away, accuracy 25 m, radius 40 m. What should the app say?

05Say uncertain when it is

Say uncertain when it is

06Fix the trip tracker

Fix the trip tracker

The local map first needs the correct east–west scale. Adding those distances over a track then exposes cancellation on short segments and the flat map’s error on long hops. The arrival check adds another source of uncertainty: a stable distance between reported points still needs an assumed position-error range before it can justify the customer’s message.

A delivery app’s trip tracking

Distance on a flat map, trip length from GPS fixes, then the arrival check.

  1. easy · M-STABILITY-V4-1 Distance on a flat map
  2. medium · M-STABILITY-V4-2 Trip length from GPS fixes
  3. hard · M-STABILITY-V4-3 Has the courier arrived?
In the frontend An arrival status from the Geolocation API in Next.js and Svelte Optional

The browser’s Geolocation API reports coords.accuracy with every fix. A tracking page applies the same assumed-bound policy: “Arrived” when distance plus accuracy is inside the radius, and “Nearby” while the range crosses it. This remains a model based on an estimated GPS accuracy, rather than proof of physical arrival.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

// Model policy: treat the estimated accuracy as a bound; it is not a GPS guarantee.
import { useEffect, useState } from "react";

const R = 6_371_000;
const rad = (degrees: number) => (degrees * Math.PI) / 180;

function distance(lat1: number, lon1: number, lat2: number, lon2: number): number {
  const dLat = Math.sin(rad(lat2 - lat1) / 2);
  const dLon = Math.sin(rad(lon2 - lon1) / 2);
  const h = dLat * dLat + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * dLon * dLon;

  return 2 * R * Math.asin(Math.sqrt(Math.min(1, h)));
}

export function ArrivalStatus({
  drop,
  radius = 40
}: {
  drop: { lat: number; lon: number };
  radius?: number;
}) {
  const [status, setStatus] = useState("Waiting for location");

  useEffect(() => {
    const watch = navigator.geolocation.watchPosition(
      ({ coords }) => {
        const d = distance(coords.latitude, coords.longitude, drop.lat, drop.lon);
        setStatus(
          d + coords.accuracy <= radius
            ? "Arrived"
            : d - coords.accuracy > radius
              ? "On the way"
              : "Nearby"
        );
      },
      () => setStatus("Location unavailable")
    );

    return () => navigator.geolocation.clearWatch(watch);
  }, [drop, radius]);

  return <p>{status}</p>;
}

Check this idea later
Would printing the law-of-cosines result with 15 decimals recover a 0.27 m segment?
A fix is 100 m away with 10 m accuracy and a 40 m radius. What is the decision?
Sources

Values above were computed with a 60-digit reference and run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The courier and trips are a worked model on a sphere of radius 6,371 km.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.