Created
September 14, 2020 21:40
-
-
Save ondrej-kvasnovsky/0fad9e4ac755b4a7050b083f92645c14 to your computer and use it in GitHub Desktop.
Cosine Similarity
This file contains 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
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