Skip to content

Instantly share code, notes, and snippets.

@ondrej-kvasnovsky
Created September 14, 2020 21:40
Show Gist options
  • Save ondrej-kvasnovsky/0fad9e4ac755b4a7050b083f92645c14 to your computer and use it in GitHub Desktop.
Save ondrej-kvasnovsky/0fad9e4ac755b4a7050b083f92645c14 to your computer and use it in GitHub Desktop.
Cosine Similarity
function cosineSimilarity(a: number[], b: number[]) {
let dotProduct = 0;
let magnitudeA = 0;
let magnitudeB = 0;
for (let i = 0; i < a.length; i++) {
dotProduct += (a[i] * b[i]);
magnitudeA += (a[i] * a[i]);
magnitudeB += (b[i] * b[i]);
}
magnitudeA = Math.sqrt(magnitudeA);
magnitudeB = Math.sqrt(magnitudeB);
const similarity = (dotProduct) / ((magnitudeA) * (magnitudeB));
return similarity;
}
const array1 = [1, 0, 0, 1];
const array2 = [1, 0, 0, 0];
const p = cosineSimilarity(array1, array2);
console.log(p);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment