Skip to content

Instantly share code, notes, and snippets.

@taddeimania
Created October 28, 2015 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taddeimania/cfbae97877d0aa3b1e10 to your computer and use it in GitHub Desktop.
Save taddeimania/cfbae97877d0aa3b1e10 to your computer and use it in GitHub Desktop.
Calculate the distance between two feature vectors.
function euclideanDistance(v1, v2) {
return v1.map(
(e, i) => [v1[i], v2[i]]
).map(
(a) => a.reduce(
(prev, cur) => prev - cur
)
).map(
(e) => e ** 2
).reduce(
(prev, cur) => prev + cur
) ** .5;
};
// Identical feature sets result in a distance of: 0
let testResultSet1 = [1, 3, 5, 1, 1, 1, 1];
let ecd_1 = euclideanDistance(
testResultSet1, testResultSet1
);
console.log(ecd_1);
// >> 0
// Nearly Identical feature sets result in a distance of: ~1.4 (close to zero)
let testResultSet2 = [1, 3, 5, 2, 1, 2, 1];
let ecd_2 = euclideanDistance(
testResultSet1, testResultSet2
);
console.log(ecd_2);
// >> 1.4142135623730951
// Very different feature sets result in a distance of: ~8.3 (the higher, the worse of a match it is.)
let testResultSet3 = [2, 5, 1, 2, 5, 5, 5];
let ecd_3 = euclideanDistance(
testResultSet1, testResultSet3
);
console.log(ecd_3);
// >> 8.366600265340756
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment