Manhattan Distance Formula: A Stroll Through the City Grid
Imagine you're a tourist in New York City, and you have to walk from the Empire State Building to another famous landmark. If you've ever been to a city with a grid system, like Manhattan, you'll notice that you can't always walk diagonally through buildings (unlike birds who can fly in a straight line). Instead, you walk along streets, taking right angles. The Manhattan Distance is a measure of the distance you'd walk, not the straight line or "as-the-crow-flies" distance.
Visualizing the Route

In the illustration above, the distance from the Empire State Building to the first corner is the horizontal distance. It's computed by the difference in the x-coordinates: |x_2 - x_1|
. Likewise, the vertical distance, from the corner to the destination, is |y_2 - y_1|
. By summing up these distances, we get the total Manhattan distance.
Why the Absolute Value?
The absolute value ensures that the distance is always positive, regardless of the direction. Think about it: If you were to walk 5 blocks north or 5 blocks south, the effort (or distance) is the same. It's 5 blocks!
Formalizing the Formula
Given two points (x_1, y_1)
and (x_2, y_2)
, the Manhattan Distance d
between them is:
d = |x_1 - x_2| + |y_1 - y_2|
When it comes to vectors, the formula can be expanded:
d = Σ|A_i – B_i|
Where:
A
andB
are vectors.i
represents thei^{th}
element in each vector.
Manhattan Distance in Machine Learning
In machine learning, the Manhattan distance is often used in clustering algorithms or when we need a distance metric between two datasets. For example, it's used in the K-Nearest Neighbors algorithm to find data points that are "close" to a given point.
Code to Compute Manhattan Distance
To make our life simpler, Python provides libraries that readily compute this for us. When you run the code, it will display:
1Output: Manhattan Distance between [2, 4, 4, 6] and [5, 5, 7, 8] is 9
This means that if these vectors were points in a city, you'd have to walk 9 blocks to get from point A to point B!
xxxxxxxxxx
// Define two vectors
const A = [2, 4, 4, 6];
const B = [5, 5, 7, 8];
​
// Calculate Manhattan Distance between the vectors
function cityBlockDistance(vec1, vec2) {
if (vec1.length !== vec2.length) {
throw new Error("Vectors must be of the same length");
}
let sum = 0;
for (let i = 0; i < vec1.length; i++) {
sum += Math.abs(vec1[i] - vec2[i]);
}
return sum;
}
​
const manhattanDistance = cityBlockDistance(A, B);
console.log(`Manhattan Distance between ${A} and ${B} is ${manhattanDistance}`);