geo.distance
Great-circle distance in metres between two latitude/longitude points (haversine), to the millimetre.
1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra
Pinned by 19 tests, run in TypeScript, Python and Rust.
What it does
The great-circle distance between two latitude/longitude points, in metres, by the haversine formula, rounded to the millimetre.
## The model
For example
distance(51.507, -0.128, 48.857, 2.352)→ 343,556.535 London to Parisdistance(40.641, -73.778, 51.47, -0.454)→ 5,540,018.97 JFK to Heathrowdistance(-33.869, 151.209, -37.814, 144.963)→ 713,428.466 Sydney to Melbourne, southern and eastern hemispheres
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
export function distance(fromLat: number, fromLng: number, toLat: number, toLng: number): number
| fromLat | float | degrees, -90 to 90 |
| fromLng | float | degrees, -180 to 180 |
| toLat | float | degrees, -90 to 90 |
| toLng | float | degrees, -180 to 180 |
| returns | float | metres on a sphere of radius 6,371,008.8 m, rounded to 3 decimals |
Your code names it in one line, in the file that uses it
import { distance } from "#fune/geo.distance@^1";
/**
* Great-circle distance between two points, by the haversine formula, on a
* sphere of the IUGG mean Earth radius, in metres rounded to millimetres.
*
* Why this does not call Math.sin, Math.cos or Math.atan2: those come from
* each platform's maths library, which is allowed to differ in the last bit
* between JavaScript, Python and Rust. Rounding afterwards does not fully hide
* that, because a value that lands next to a rounding boundary can go either
* way. The trigonometry below uses only operations IEEE 754 requires to be
* correctly rounded (+ - * / sqrt floor), in a fixed order, so the unrounded
* result is the same double in every language, and the rounding is then only
* presentation.
*/
// IUGG mean radius R1 = (2a + b) / 3 of the GRS 80 ellipsoid (Moritz,
// "Geodetic Reference System 1980", Journal of Geodesy 74 (2000) 128-133).
const EARTH_RADIUS_METRES = 6371008.8;
const PI = 3.141592653589793;
const HALF_PI = PI / 2;
const DEGREES = PI / 180;
// Taylor coefficients, each one correctly-rounded division.
const S3 = -1 / 6, S5 = 1 / 120, S7 = -1 / 5040, S9 = 1 / 362880, S11 = -1 / 39916800;
const S13 = 1 / 6227020800, S15 = -1 / 1307674368000, S17 = 1 / 355687428096000;
const C2 = -1 / 2, C4 = 1 / 24, C6 = -1 / 720, C8 = 1 / 40320, C10 = -1 / 3628800;
const C12 = 1 / 479001600, C14 = -1 / 87178291200, C16 = 1 / 20922789888000, C18 = -1 / 6402373705728000;
const A3 = -1 / 3, A5 = 1 / 5, A7 = -1 / 7, A9 = 1 / 9, A11 = -1 / 11;
const A13 = 1 / 13, A15 = -1 / 15, A17 = 1 / 17, A19 = -1 / 19, A21 = 1 / 21;
// sin and cos on |r| <= pi/4, where the series converge to well below an ulp.
function sinSmall(r: number): number {
const s = r * r;
let p = S17;
p = S15 + s * p;
p = S13 + s * p;
p = S11 + s * p;
p = S9 + s * p;
p = S7 + s * p;
p = S5 + s * p;
p = S3 + s * p;
return r + r * s * p;
}
function cosSmall(r: number): number {
const s = r * r;
let p = C18;
p = C16 + s * p;
p = C14 + s * p;
p = C12 + s * p;
p = C10 + s * p;
p = C8 + s * p;
p = C6 + s * p;
p = C4 + s * p;
p = C2 + s * p;
return 1 + s * p;
}
// Reduce to a quarter turn k and a remainder |r| <= pi/4.
function sinCos(x: number): [number, number] {
const k = Math.floor(x / HALF_PI + 0.5);
const r = x - k * HALF_PI;
const sr = sinSmall(r);
const cr = cosSmall(r);
const quadrant = ((k % 4) + 4) % 4;
if (quadrant === 0) return [sr, cr];
if (quadrant === 1) return [cr, -sr];
if (quadrant === 2) return [-sr, -cr];
return [-cr, sr];
}
// atan for 0 <= u <= 1: halve the angle three times (tan(t/2) = u / (1 + sqrt(1 + u^2)))
// so the series runs on |u| <= tan(pi/32), then scale back by 8.
function atanUnit(u: number): number {
let v = u;
v = v / (1 + Math.sqrt(1 + v * v));
v = v / (1 + Math.sqrt(1 + v * v));
v = v / (1 + Math.sqrt(1 + v * v));
const s = v * v;
let p = A21;
p = A19 + s * p;
p = A17 + s * p;
p = A15 + s * p;
p = A13 + s * p;
p = A11 + s * p;
p = A9 + s * p;
p = A7 + s * p;
p = A5 + s * p;
p = A3 + s * p;
return 8 * (v + v * s * p);
}
// atan2 for y >= 0 and x >= 0, which is all haversine needs.
function atan2Positive(y: number, x: number): number {
if (x === 0) return y === 0 ? 0 : HALF_PI;
const t = y / x;
return t > 1 ? HALF_PI - atanUnit(x / y) : atanUnit(t);
}
// Half away from zero on the binary64 value; + 0 turns -0 into 0.
function roundTo(x: number, scale: number): number {
const y = Math.abs(x) * scale;
let r = Math.floor(y);
if (y - r >= 0.5) r += 1;
const out = r / scale;
return (x < 0 ? -out : out) + 0;
}
function checkLatitude(value: number): void {
if (typeof value !== "number" || !Number.isFinite(value)) {
throw new TypeError("latitude must be a finite number of degrees");
}
if (value < -90 || value > 90) throw new RangeError("latitude must be between -90 and 90 degrees");
}
function checkLongitude(value: number): void {
if (typeof value !== "number" || !Number.isFinite(value)) {
throw new TypeError("longitude must be a finite number of degrees");
}
if (value < -180 || value > 180) throw new RangeError("longitude must be between -180 and 180 degrees");
}
export function distance(fromLat: number, fromLng: number, toLat: number, toLng: number): number {
checkLatitude(fromLat);
checkLongitude(fromLng);
checkLatitude(toLat);
checkLongitude(toLng);
const phi1 = fromLat * DEGREES;
const phi2 = toLat * DEGREES;
// A longitude difference of 359 degrees is a 1 degree step across the
// antimeridian; sin^2 of the half-angle is the same either way, so no
// wrapping is needed.
const [sinHalfLat] = sinCos(((toLat - fromLat) * DEGREES) / 2);
const [sinHalfLng] = sinCos(((toLng - fromLng) * DEGREES) / 2);
const [, cos1] = sinCos(phi1);
const [, cos2] = sinCos(phi2);
let a = sinHalfLat * sinHalfLat + cos1 * cos2 * sinHalfLng * sinHalfLng;
// Rounding can push a a hair outside [0, 1] for antipodal points.
if (a < 0) a = 0;
if (a > 1) a = 1;
// atan2 rather than asin(sqrt(a)): stays accurate for antipodal points too.
const c = 2 * atan2Positive(Math.sqrt(a), Math.sqrt(1 - a));
return roundTo(EARTH_RADIUS_METRES * c, 1000);
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add geo.distance
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./geo.distance-1.0.0-typescript.fune, or fetch it from a terminal with fune pull geo.distance@1.0.0:typescript.
The whole function, every language, is one file too: geo.distance-1.0.0.fune, 23,430 bytes, sha256 701b702975d223bf7fdc1a539827f06ebd9962b8f8d84d0c1216bca38fc31935. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
// fune: before geo.distance
after — your function gets the result and the arguments, and returns the final result.
// fune: after geo.distance
replace — it requires no other capability, so there is no dependency to replace.
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show geo.distance --steps.
// fune: step geo.distance after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
| Case | Arguments | Expected | |
|---|---|---|---|
| London to Paris | 51.507, -0.128, 48.857, 2.352 | → | 343,556.535 |
| JFK to Heathrow | 40.641, -73.778, 51.47, -0.454 | → | 5,540,018.97 |
| Sydney to Melbourne, southern and eastern hemispheres | -33.869, 151.209, -37.814, 144.963 | → | 713,428.466 |
| Nashville to Los Angeles, the classic haversine example, on the IUGG mean radius | 36.12, -86.67, 33.94, -118.4 | → | 2,886,448.43 |
| one degree of longitude on the equator is pi R / 180 | 0, 0, 0, 1 | → | 111,195.08 |
| one degree of latitude is the same length on a sphere | 0, 0, 1, 0 | → | 111,195.08 |
| across the antimeridian is one degree, not 359 (naive longitude difference gets this wrong) | 0, 179.5, 0, -179.5 | → | 111,195.08 |
| half way round the equator is half the circumference | 0, 0, 0, 180 | → | 20,015,114.442 |
| pole to pole, antipodal | 90, 0, -90, 0 | → | 20,015,114.442 |
| over the north pole: 89.9N 0E to 89.9N 180E is 0.2 degrees | 89.9, 0, 89.9, 180 | → | 22,239.016 |
Show the other 9 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the same pole at two longitudes is the same point | -90, 0, -90, 123 | → | 0 |
| identical points are zero | 51.507, -0.128, 51.507, -0.128 | → | 0 |
| about a metre apart keeps millimetre accuracy (the acos formula loses it) | 51.5, -0.1, 51.5, -0.1 | → | 1.001 |
| about 11 centimetres | 10, 20, 10, 20 | → | 0.111 |
| the order of the points does not matter | 48.857, 2.352, 51.507, -0.128 | → | 343,556.535 |
| latitude above 90 is an error | 91, 0, 0, 0 | → | error: latitude must be between -90 and 90 degrees |
| latitude below -90 is an error | 0, 0, -90.5, 0 | → | error: latitude must be between -90 and 90 degrees |
| longitude above 180 is an error, not silently wrapped | 0, 181, 0, 0 | → | error: longitude must be between -180 and 180 degrees |
| a coordinate that is not a number is an error | 51.5, 0, 0, 0 | → | error: latitude must be a finite number of degrees |
More from the author
The Earth is taken as a sphere of radius 6,371,008.8 m, the IUGG mean radius R1 = (2a + b) / 3 of the GRS 80 ellipsoid (H. Moritz, "Geodetic Reference System 1980", Journal of Geodesy 74 (2000) 128-133; also Bulletin Géodésique 54 (1980)). Many snippets use 6,371,000 m or the equatorial 6,378,137 m; those give different answers, which is why the radius is part of the contract.
A sphere is not the Earth. Against the WGS 84 ellipsoid (Vincenty, Karney) the haversine distance is off by up to about 0.5%. Use this for "how far is the nearest depot", delivery radii and sorting by distance, not for surveying. The millimetre rounding is about reproducibility, not accuracy.
Longitudes do not need wrapping: 179.5 to -179.5 is 1 degree across the antimeridian, because the formula only uses sin² of half the difference. Coordinates outside -90..90 and -180..180 are errors rather than being wrapped, since they usually mean latitude and longitude were swapped.
The result uses atan2(√a, √(1−a)) rather than asin(√a). For points closer than a metre or so it keeps millimetre accuracy, where the spherical law of cosines (acos) loses it. Near-antipodal points are ill-conditioned for any haversine in double precision: within about a degree of the antipode the answer can be a few millimetres from the exact spherical value (elsewhere it is within 1e-7 m).
## Why the answers are identical in every language
JavaScript's Math.sin, Python's math.sin and Rust's f64::sin come from different maths libraries, which are allowed to differ in the last bit. Rounding to millimetres hides that almost always, but not always: a value that lands on a rounding boundary can go either way.
So this capability does not call them. It carries its own sin, cos and atan, built only from operations IEEE 754 requires to be correctly rounded (+ − × ÷, sqrt, floor), evaluated in the same order in all three languages: range reduction to a quarter turn, fixed-length Taylor polynomials in Horner form, and angle halving for atan. No language fuses a multiply and an add behind your back (JavaScript and Python cannot; Rust does not without an explicit mul_add). The unrounded distance is therefore the same double in TypeScript, Python and Rust, and the rounding step is only presentation. This was checked on 4,000 random pairs (including near-coincident and near-antipodal ones): the unrounded and rounded results were bit-for-bit identical in all three.
## Rounding
Half away from zero, applied to the binary64 value: y = d × 1000, r = floor(y), r + 1 if y − r ≥ 0.5, result r / 1000. Not Python's round(), which rounds halves to even.
Files
| Path | Bytes |
|---|---|
| README.md | 2,805 |
| impl/python.py | 4,692 |
| impl/rust.rs | 5,974 |
| impl/typescript.ts | 5,189 |
| vectors.json | 2,378 |