Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.