Skip to main content

Euclidean and Manhattan Distance

Euclidean Distance

Euclidean distance is the straight-line distance between two points in Euclidean space. For two points (x1, y1) and (x2, y2), the Euclidean distance is given by the formula:

Euclidean Distance = sqrt{(x2 - x1)^2 + (y2 - y1)^2}

JavaScript Implementation

function euclideanDistance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}

console.log(euclideanDistance(1, 2, 4, 6)); // Output: 5

Manhattan Distance

Manhattan distance, also known as "taxicab" or "city block" distance, is the distance between two points measured along the axes at right angles. For two points ( (x_1, y_1) ) and ( (x_2, y_2) ), the Manhattan distance is given by:

Manhattan Distance = |x2 - x1| + |y2 - y1|

JavaScript Implementation

function manhattanDistance(x1, y1, x2, y2) {
return Math.abs(x2 - x1) + Math.abs(y2 - y1);
}

console.log(manhattanDistance(1, 2, 4, 6)); // Output: 7

Use Cases

  • Euclidean Distance is often used in geometric problems, clustering algorithms (like k-means), and when calculating the shortest distance between two points.
  • Manhattan Distance is useful when movement is restricted to horizontal and vertical directions, such as grid-based systems or city road networks.