Skip to content

Instantly share code, notes, and snippets.

@worbit
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save worbit/dd35812cf47ac031f33a to your computer and use it in GitHub Desktop.
Save worbit/dd35812cf47ac031f33a to your computer and use it in GitHub Desktop.
Calculate cosine similarity between two double[]'s
/**
*
* @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