Skip to content

Instantly share code, notes, and snippets.

@christianscott
Created January 8, 2020 06:01
Show Gist options
  • Save christianscott/134947fa559030b25adbabdd61671432 to your computer and use it in GitHub Desktop.
Save christianscott/134947fa559030b25adbabdd61671432 to your computer and use it in GitHub Desktop.
N-dimensional Euclidean distance
/**
* Calculates the euclidean distance between two N-dimensional
* points, represented as arrays of length N.
*/
export function euclideanDistance<P extends [number, ...number[]]>(
p1: P,
p2: P,
): number {
if (p1.length === 1) {
return Math.abs(p1[0] - p2[0]);
}
let sumOfSquaredDistances = 0;
for (let i = 0; i < p1.length; i++) {
sumOfSquaredDistances += Math.pow(p1[i] - p2[i], 2);
}
return Math.sqrt(sumOfSquaredDistances);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment