Created
January 8, 2020 06:01
-
-
Save christianscott/134947fa559030b25adbabdd61671432 to your computer and use it in GitHub Desktop.
N-dimensional Euclidean distance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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