Last active
September 26, 2021 11:51
-
-
Save rloredo/8acd3f0152e4663737d44312bea4c3ad to your computer and use it in GitHub Desktop.
Calculate cosine similarity in javascript
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 cosinesim(A,B){ | |
var dotproduct=0; | |
var mA=0; | |
var mB=0; | |
for(i = 0; i < A.length; i++){ | |
dotproduct += (A[i] * B[i]); | |
mA += (A[i]*A[i]); | |
mB += (B[i]*B[i]); | |
} | |
mA = Math.sqrt(mA); | |
mB = Math.sqrt(mB); | |
var similarity = (dotproduct)/((mA)*(mB)) | |
return similarity; | |
} | |
var array1 = [1,1,0,0,0,0,0,0,0,0]; | |
var array2 = [1,0,1,1,1,1,1,1,1,1]; | |
var p = cosinesim(array1,array2); | |
console.log(p); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment