Skip to content
DSA in JavaScript
More Math

Euclidean Distance

Algorithm · Stretch

Level: Stretch

In mathematics, the Euclidean distance between two points in Euclidean space is the length of a line segment between the two points. It can be calculated from the Cartesian coordinates of the points using the Pythagorean theorem, therefore occasionally being called the Pythagorean distance.

Distance formulas

One dimension

The distance between any two points on the real line is the absolute value of the numerical difference of their coordinates

Two dimensions

Higher dimensions

In three dimensions, for points given by their Cartesian coordinates, the distance is

Example: the distance between the two points (8,2,6) and (3,5,7):

In general, for points given by Cartesian coordinates in n-dimensional Euclidean space, the distance is

Code

euclideanDistance.js
/**
 * @typedef {import('../matrix/Matrix.js').Matrix} Matrix
 */

import * as mtrx from '../matrix/Matrix';

/**
 * Calculates the euclidean distance between 2 matrices.
 *
 * @param {Matrix} a
 * @param {Matrix} b
 * @returns {number}
 * @trows {Error}
 */
const euclideanDistance = (a, b) => {
  mtrx.validateSameShape(a, b);

  let squaresTotal = 0;

  mtrx.walk(a, (indices, aCellValue) => {
    const bCellValue = mtrx.getCellAtIndex(b, indices);
    squaresTotal += (aCellValue - bCellValue) ** 2;
  });

  return Number(Math.sqrt(squaresTotal).toFixed(2));
};

export default euclideanDistance;

References

Spotted a mistake or something unclear? Report it on GitHub.

On this page