Skip to content

Instantly share code, notes, and snippets.

@lunaroyster
Last active December 2, 2017 08:53
Show Gist options
  • Save lunaroyster/f24335c408b2cd86048be7463e9ef16e to your computer and use it in GitHub Desktop.
Save lunaroyster/f24335c408b2cd86048be7463e9ef16e to your computer and use it in GitHub Desktop.
var cosineSimilarity = (A, B)=> {
let dotProduct = (a, b)=> {
if(a.length!=b.length) throw Error("Bad vector");
let sum = 0;
for(let i = 0; i<a.length; i++) {
sum+=(a[i]*b[i]);
}
return sum;
};
let magnitude = (a)=> {
let squareSum = 0;
for(let i of a) {
squareSum+=i**2;
}
return squareSum**0.5
};
let AdotB = dotProduct(A, B);
let Amag = magnitude(A);
let Bmag = magnitude(B);
return AdotB/(Amag*Bmag);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment