Manhattan Distance Calculator
Compute the Manhattan (L1 / taxicab / city-block) distance between two points or two vectors of any dimension, in your browser. See the full per-dimension working, the substituted expression, and the Euclidean and Chebyshev comparisons. Matches scikit-learn and SciPy, no signup, nothing uploaded.
How it works
Manhattan distance, also called L1, taxicab, or city-block distance, is the distance between two points measured along axis-aligned moves, the way a taxi travels a rectangular street grid rather than cutting diagonally. For two equal-length vectors a = [a₁…aₙ] and b = [b₁…bₙ], it is the sum of the absolute coordinate differences. It is the metric scikit-learn calls manhattan_distances and SciPy calls cityblock.
d₁(a, b) = Σ |aᵢ − bᵢ| = |a₁ − b₁| + … + |aₙ − bₙ|
The tool computes this in three steps:
- Per-dimension difference. Subtract the vectors coordinate by coordinate:
dᵢ = aᵢ − bᵢ. - Absolute value and sum. Take
|dᵢ|for each dimension and add them. That sumΣ |dᵢ|is the Manhattan distance, no squaring, no square root. - Comparison metrics. Over the same differences the tool also reports Euclidean
√(Σ dᵢ²)and Chebyshevmax |dᵢ|, the L2 and L∞ members of the same Minkowski family.
One family, three names
All three metrics are special cases of the Minkowski distance dₚ = (Σ |aᵢ − bᵢ|ᵖ)^(1/p): p = 1 gives Manhattan, p = 2 gives Euclidean, and p → ∞ gives Chebyshev. Because Manhattan is the p = 1 case, the calculator uses that general form as an independent cross-check. It recomputes (Σ |dᵢ|¹)^(1/1) and confirms it reconciles with the direct Σ |dᵢ| sum, exactly as SciPy's minkowski(u, v, 1) equals cityblock(u, v). All arithmetic is double-precision and is rounded only for display, using the decimal places you pick, so even inputs around 10⁹ stay exact.
If you want the other members of the family with their own working, each has its own page here: the Euclidean distance calculator for the straight-line L2 case, the Chebyshev distance calculator for the L∞ or chessboard case, and the Minkowski distance calculator if you want to set p yourself and watch the number move between them.
Why it is a proper metric
Manhattan distance satisfies the four conditions that make a function a metric, which is why clustering and nearest-neighbour algorithms accept it as a drop-in alternative to Euclidean. It is non-negative, because every term is an absolute value. It is zero only for identical points, since a sum of non-negative terms is zero only when each term is. It is symmetric, because |aᵢ − bᵢ| = |bᵢ − aᵢ|, so swapping vector A and vector B leaves the answer unchanged. And it obeys the triangle inequality, d(a, c) ≤ d(a, b) + d(b, c). A quick check: from (0, 0) to (2, 3) is 5, from (2, 3) to (5, 7) is 7, and from (0, 0) to (5, 7) is 12, so the inequality holds with equality here because (2, 3) sits on a monotone grid path between the two ends. That equality case is a feature of grid geometry: unlike the straight line, a taxicab route between two points is almost never unique, and every staircase route of the same width and height has the same length.
Scale, units and normalisation
L1 adds raw coordinate gaps, so it inherits whatever units your features carry. Mix a salary column in rupees with an age column in years and the salary differences will swamp the total, not because they matter more but because they are numerically larger. The usual fix before any distance metric is to put every feature on a comparable scale, either min-max to the 0 to 1 range or a z-score built from the column mean and standard deviation. Manhattan is gentler about this than Euclidean, since squaring magnifies a large gap while an absolute value does not, but gentler is not immune. If what you care about is the direction of two vectors rather than their magnitude, a distance metric is the wrong family altogether and cosine similarity is the measure you want.
Weighted and normalised variants
Plain L1 gives every coordinate the same say. Weighted Manhattan distance, d = Σ wᵢ |aᵢ − bᵢ|, attaches a multiplier to each one, which is how you stop a single wide-ranging column from deciding the answer on its own. Setting every weight to 1 returns the figure this calculator shows, so you can treat the output here as the baseline and reason about what a weight changes from there. Two weighting schemes are common enough to have their own names. Dividing each gap by the sum of the two magnitudes, |aᵢ − bᵢ| / (|aᵢ| + |bᵢ|), gives the Canberra distance, which makes small coordinates count as much as large ones and suits count data where a 1-to-2 jump matters more than a 1000-to-1001 one. Weighting by the inverse covariance of the whole dataset instead gives the Mahalanobis distance, which also removes correlation between features rather than only rescaling them. Neither is better in the abstract: pick the one whose assumption about your columns is actually true.
What it is not: road and map distance
The taxicab picture tempts people into using L1 on latitude and longitude. Two problems follow. First, a degree of longitude is not a fixed number of kilometres, it shrinks as you move away from the equator, so adding degree gaps across the two axes produces a number in no unit at all. Near Colombo, at about 6.9° N, a degree of latitude is roughly 110.6 km and a degree of longitude roughly 110.5 km, so close that the mistake hides; at 50° N the longitude degree has shrunk to about 71.6 km and the same formula is visibly wrong. Second, real street grids are not grids. Colombo, Kandy and Galle are shaped by coastline, rail lines and hills, so the shortest driveable route is rarely the sum of two axis legs. Use L1 for abstract feature vectors and for four-connected game or warehouse grids; for an actual journey between two Sri Lankan towns use the Sri Lanka road distance calculator, which measures along the road network rather than along the axes.
Edge cases the tool handles
- Different lengths. Two vectors of unequal dimension have no Manhattan distance, so the tool refuses the pair and names both lengths instead of silently padding or returning NaN.
- Identical points. The distance is exactly 0 and is labelled as an identical point. Nothing divides by anything, so there is no special case to guard.
- Negative coordinates. Signs are absorbed by the absolute value. From (−1, −2) to (3, 1) the differences are −4 and −3, so L1 is 7, the same answer as a pair sitting entirely in the positive quadrant with the same gaps.
- Decimals and floating point. Binary floating point cannot hold 0.1 exactly, so a sum of decimals can land a few quadrillionths off a round figure. The arithmetic keeps full double precision and only the display is rounded, to the number of decimal places you choose.
- Very large values. Coordinates around 10⁹ give an L1 total around 2 × 10⁹, far below the double-precision ceiling near 1.8 × 10³⁰⁸, so nothing overflows. Scientific notation such as
1e9is accepted in the input. - One dimension. With a single coordinate each, every metric in the family collapses to the same thing: the absolute difference
|a₁ − b₁|. - Very long vectors. Up to 10,000 components per vector are parsed, which covers pasted embeddings. The per-dimension table truncates its rows so the page stays fast, while the total is computed over every component.
Manhattan vs Euclidean vs Chebyshev
The three metrics below are computed from the same per-dimension differences and answer three different questions about the same pair of points: how far along the grid, how far through the air, and how far along the single worst axis. The values in the last column are all for the 2D pair a = (2, 3) and b = (5, 7), whose differences are 3 and 4.
| Metric | Formula | Minkowski p | Picture | (2,3) to (5,7) |
|---|---|---|---|---|
| Manhattan (L1) | Σ |aᵢ − bᵢ| | 1 | Street grid, no diagonals | 7 |
| Euclidean (L2) | √(Σ (aᵢ − bᵢ)²) | 2 | Straight line through the block | 5 |
| Chebyshev (L∞) | max |aᵢ − bᵢ| | to ∞ | King moves on a chessboard | 4 |
| Minkowski, p = 3 | (Σ |aᵢ − bᵢ|³)^(1/3) | 3 | Between L2 and L∞ | 4.497941 |
Two things to read off that table. First, the ordering L∞ ≤ L2 ≤ L1 is not a coincidence: raising p always lowers or keeps the total, because larger p shifts weight onto the single biggest gap. Chebyshev keeps only that gap, 4, while Manhattan counts every gap in full, 3 + 4. Second, the spread between 4 and 7 is a measure of how evenly the difference is distributed. Two points that differ in one coordinate only give the same number for all three metrics, and the more coordinates share the difference, the further L1 pulls ahead.
Worked examples
Where Manhattan distance is used
The metric earns its place wherever movement or cost is additive across independent axes, and wherever a single large difference should not be allowed to dominate a total.
- Grid pathfinding. On a map where an agent may step up, down, left or right but not diagonally, Manhattan distance is the exact shortest path when there are no obstacles, which makes it the standard admissible heuristic for A* on four-connected grids. Use Chebyshev instead when diagonal steps are allowed and cost the same.
- Nearest neighbours and clustering. KNN classifiers accept it as
metric="manhattan", and k-medians is the L1 counterpart of k-means. Because L1 does not square the gaps, a single noisy feature moves the cluster assignment less than it would under L2. - High-dimensional and sparse data. As dimensions grow, Euclidean distances between random points bunch together. L1 degrades more slowly, which is why it is a common first thing to try when nearest-neighbour results on wide feature tables look arbitrary.
- Regularisation. The L1 norm is the same sum of absolute values measured from the origin, and it is what lasso regression penalises. Its habit of driving coefficients to exactly zero, rather than merely small, comes from the diamond shape of the L1 unit ball, the same shape that makes taxicab circles squares stood on a corner.
- Layout and logistics. Chip routing, warehouse picking and gantry or plotter movement are all constrained to axes, so the cost of a move is the sum of its per-axis legs rather than a diagonal.
- Binary and categorical features. Over one-hot or 0/1 columns, L1 counts how many positions differ, which makes it interchangeable with Hamming distance for that kind of data.
Manhattan distance in code
Every snippet below returns the same 5.0 for a = [1, 2, 3] and b = [4, 0, 3], which is the first worked example above. Use the calculator to check a value by hand before you trust a pipeline that computes thousands of them.
Python
import numpy as np
from scipy.spatial.distance import cityblock, minkowski
from sklearn.metrics.pairwise import manhattan_distances
a = np.array([1, 2, 3])
b = np.array([4, 0, 3])
np.abs(a - b).sum() # 5
cityblock(a, b) # 5.0
minkowski(a, b, 1) # 5.0 (p = 1 is Manhattan)
manhattan_distances([a], [b]) # array([[5.]]) pairwise matrixSQL
With both points on one row, ABS and addition are enough. With one coordinate per row, join the two vectors on the dimension index and aggregate with SUM.
-- one row per point pair
SELECT ABS(x1 - x2) + ABS(y1 - y2) AS manhattan
FROM point_pairs;
-- long format: one row per (vector_id, dim, val)
SELECT SUM(ABS(a.val - b.val)) AS manhattan
FROM vectors a
JOIN vectors b ON b.dim = a.dim
WHERE a.vector_id = 1
AND b.vector_id = 2;Excel and Google Sheets
For two points on a single row, ABS and plus signs are all you need. For vectors of any length laid out as two columns, SUMPRODUCT folds the whole sum into one cell. Both formulas are identical in Google Sheets; only Excel before 2019 needs Ctrl+Shift+Enter on the array version.
' two points on one row: A2,B2 = point a C2,D2 = point b
=ABS(A2-C2)+ABS(B2-D2) ' 5 for (1,2) and (4,0)
' n-D vectors in two columns: A2:A100 = a, B2:B100 = b
=SUMPRODUCT(ABS(A2:A100-B2:B100))
' weighted L1, weights in C2:C100
=SUMPRODUCT(C2:C100, ABS(A2:A100-B2:B100))JavaScript
const manhattan = (a, b) => {
if (a.length !== b.length) throw new Error("length mismatch");
return a.reduce((sum, ai, i) => sum + Math.abs(ai - b[i]), 0);
};
manhattan([1, 2, 3], [4, 0, 3]); // 5Two traps worth knowing. In SQL, a missing dimension on either side quietly drops out of an inner join, so a 3-component vector compared against a 2-component one returns a number instead of an error. Check the row counts match first. In NumPy, broadcasting will happily compare shapes that differ, so assert a.shape == b.shape rather than relying on an exception.
Frequently asked questions
Sources & references
- scikit-learn: sklearn.metrics.pairwise.manhattan_distances (the canonical L1 definition this tool matches)
- SciPy: scipy.spatial.distance.cityblock (the city-block / L1 definition and naming)
- SciPy: scipy.spatial.distance.minkowski (the general dₚ form; p = 1 is the cross-check route)
The formulas on this page were last cross-checked against these sources on 2026-06-11. Manhattan distance is a stable mathematical definition, so this tool needs no rate or schedule updates, only the worked examples are periodically re-reconciled.
Related tools
Comments & feedback
Spotted a bug or want an improvement? Tell us, our team reviews every comment, and good ideas get built. Comments are public and anonymous.
Found a bug, edge case, or want to suggest an improvement?
Email me at [email protected] , most fixes ship within 24 hours.