Distance metrics explained
Measuring how far apart two things are sounds simple, but there is more than one right answer. A distance metric is a rule that turns two objects into one number, and the right rule depends on what the objects are: points, directions, texts, sets or places on a globe. This page explains what makes a rule a metric, how the nine metrics of the app are defined, what their circles of equal distance look like, and where each one is used, from GPS navigation to search engines and machine learning.
What makes a distance a metric
In mathematics a metric is a function d(x, y) that obeys four rules: a distance is never negative; it is zero only when x and y are the same; it is symmetric, d(x, y) = d(y, x); and it satisfies the triangle inequality, d(x, z) ≤ d(x, y) + d(y, z), so a detour is never shorter than the direct way. A set with such a function is a metric space, and everything that depends on nearness, from nearest-neighbour search to clustering, works in it. Some useful measures break a rule: cosine distance and Minkowski with p < 1 fail the triangle inequality, and are then called dissimilarities rather than metrics.
Euclidean distance: the straight line
Euclidean distance is the length of the straight segment between two points, given by the theorem of Pythagoras: d = √((x₂ − x₁)² + (y₂ − y₁)²), and in n dimensions the square root of the sum of the squared differences of all coordinates. It is the distance of everyday geometry and physics, it does not change when the picture is rotated, and the points at a fixed distance from a centre form a circle (a sphere in 3D). In machine learning it is the default distance of k-nearest neighbours and k-means, which is why features are usually scaled first: otherwise the feature with the largest numbers decides everything.
Manhattan and Chebyshev: moving on a grid
Manhattan or taxicab distance adds the absolute differences, |Δx| + |Δy|, as a taxi must drive along the streets of a grid city. Between two crossings there are many shortest routes, C(|Δx| + |Δy|, |Δx|) of them on a grid of whole blocks, and all have the same length. Its circle is a diamond, a square turned by 45°. Chebyshev or chessboard distance takes only the largest difference, max(|Δx|, |Δy|): it is the number of moves a chess king needs, since a diagonal step changes both coordinates at once. Its circle is an axis-aligned square. Warehouse cranes that move in x and y at the same time travel in Chebyshev distance.
Minkowski distance: one family for all three
Minkowski distance of order p, (|Δx|ᵖ + |Δy|ᵖ)^(1/p), joins the three: p = 1 gives Manhattan, p = 2 Euclidean, and as p grows towards infinity the largest difference dominates and the distance approaches Chebyshev. These are the Lp norms of the difference vector. The circles of equal distance grow from a diamond through a circle to a square, superellipses that become rounder squares as p rises. For p below 1 the circle caves in like a star and the triangle inequality fails, so it is no longer a metric. Between the same two points the distance never increases as p grows.
Cosine similarity: comparing directions
Cosine similarity is the cosine of the angle θ between two vectors: cos θ = A·B / (‖A‖ ‖B‖), the dot product divided by the two lengths. It is 1 when the vectors point the same way, 0 at right angles and −1 when they point in opposite directions, and it does not change when either vector is stretched. That makes it the measure of choice for text: a document is turned into a vector of word counts or into an embedding, and two documents about the same subject point in a similar direction whatever their lengths. Cosine distance is 1 − cos θ; the angle itself, θ, is a true metric.
Hamming distance: differences position by position
Richard Hamming introduced his distance in 1950 for error-correcting codes: the number of positions at which two strings of the same length differ. 1011101 and 1001001 differ in two bits, karolin and kathrin in three letters. A code whose words are at least 3 apart can correct any single error, because a received word with one flipped bit is still closer to the word that was sent than to any other. Hamming distance is also used to compare DNA sequences, hashes and fingerprints. It only substitutes characters; to allow insertions and deletions as well, the Levenshtein or edit distance is used.
Jaccard and Sørensen–Dice: overlapping sets
For sets the question is how much they overlap. Paul Jaccard's index, from 1901 for comparing the plants of alpine meadows, divides the size of the intersection by the size of the union: J = |A ∩ B| / |A ∪ B|, from 0 for disjoint sets to 1 for equal ones; the Jaccard distance 1 − J is a true metric. The Sørensen–Dice coefficient, from Thorvald Sørensen and Lee Dice in the 1940s, divides twice the intersection by the sum of the sizes: 2|A ∩ B| / (|A| + |B|). It equals the F1 score of a classifier, and in image segmentation the Jaccard index is known as intersection over union (IoU).
Haversine: distance on a sphere
Over the curved surface of the Earth the shortest route between two places follows a great circle, which is why flights from Europe to North America swing north over Greenland. The haversine formula finds the central angle c between two places from their latitudes φ and longitudes λ: a = sin²(Δφ/2) + cos φ₁ cos φ₂ sin²(Δλ/2) and c = 2 asin √a; the distance is the Earth's radius times c. The haversine, hav θ = sin²(θ/2), was tabulated for navigators in the 19th century because it keeps its accuracy for small distances, where the law of cosines loses digits. With the mean radius of 6371 km the result is within about 0.5 % of the distance on the real, slightly flattened Earth.
Distances in machine learning
Many algorithms are nothing more than a distance and a rule. k-nearest neighbours classifies a point by the labels of the points closest to it; k-means groups points round the centres they are nearest to; recommender systems suggest what similar users liked; vector databases find the embeddings closest to a query, usually by cosine similarity. The choice of metric changes the answer: Manhattan is less sensitive to a single large difference than Euclidean, and in hundreds of dimensions Euclidean distances between random points become almost equal, the curse of dimensionality, which is one reason why cosine similarity is preferred for embeddings.
How the app draws the metrics
For the four plane metrics the app draws the two points on a grid, the legs |Δx| and |Δy| they are built from, the path the metric measures (a straight line, a staircase of streets, a king's walk) and the curve of all points as far from A as B is; Other metrics adds the other curves through B. Cosine draws the vectors from the origin with the angle and the two directions at the same angle from A. Hamming lines the two texts up letter by letter and marks the differences, the set metrics place the items in a Venn diagram, and haversine draws an orthographic globe with the great-circle route, the small circle of equal distance and the chord through the Earth. The Formula card works out the calculation with the numbers shown.
Поширені запитання
Why is the Manhattan distance never shorter than the Euclidean distance?
Because the straight line is the shortest path between two points, and the Manhattan route is one particular path made of horizontal and vertical pieces. In numbers: (|Δx| + |Δy|)² = Δx² + Δy² + 2|Δx||Δy| is at least Δx² + Δy². The two are equal only when the points lie on the same horizontal or vertical line; along a diagonal the Manhattan distance is √2 ≈ 1.41 times as long.
What happens to the Minkowski distance when p goes to infinity?
The largest difference takes over. If |Δx| = 8 and |Δy| = 6, then (8ᵖ + 6ᵖ)^(1/p) = 8 (1 + 0.75ᵖ)^(1/p), and 0.75ᵖ shrinks to zero, so the distance tends to 8, the Chebyshev distance. For p = 3 it is already 8.996 and for p = 10 it is 8.04.
Is Hamming distance the same as edit distance?
No. Hamming distance only compares the characters at the same positions and needs strings of equal length, so it counts substitutions only. Levenshtein or edit distance also allows inserting and deleting characters: kitten and sitting have an edit distance of 3, while their Hamming distance is not defined because their lengths differ. For strings of equal length the edit distance is never larger than the Hamming distance.
Why is the shortest flight path curved on a map?
Flat maps cannot show the sphere without distortion. A great circle, the shortest path on the globe, appears curved on most map projections, bending towards the nearer pole. On the app's globe, an orthographic view as seen from space, the route is an arc of a great circle, and the straight line between the two cities on the picture is the chord through the inside of the Earth, shorter still.
Готові спробувати?
Відкрийте PictorX у браузері — без встановлення і без кредитної картки.
Open the distance metrics app