Last active
August 29, 2015 14:07
-
-
Save worbit/dd35812cf47ac031f33a to your computer and use it in GitHub Desktop.
Calculate cosine similarity between two double[]'s
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
/** | |
* | |
* @param one first Vector | |
* @param two second Vector | |
* @return cosine similarity as defined by <pre>dot(one,two) / ||one|| * ||two||</pre> | |
* returns 1 for same direction (similar)<br> | |
* returns 0 for perpendicular<br> | |
* returns -1 for opposite direction | |
*/ | |
public double getCosineDistance(double[] one, double[] two) { | |
double mag1 = 0; | |
for (double d : one) { | |
mag1 += d*d; | |
} | |
//magnitude of first: square root of sum of squares | |
mag1 = Math.pow(mag1, 0.5); | |
double mag2 = 0; | |
for (double d : two) { | |
mag2 += d*d; | |
} | |
//magnitude of second: square root of sum of squares | |
mag2 = Math.pow(mag2, 0.5); | |
//calculate dot product | |
double dot = 0; | |
for (int i=0; i<one.length; i++) { | |
dot += one[i]*two[i]; | |
} | |
//result is dot product divided by product of magnitudes | |
return dot / (mag1*mag2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment