Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * this method finds the vector similarity between two arrays between 0 and 1
- * where 1 is the highest value of similarity
- * returns to within a margin of error because even double precision floats
- * in java are not perfect.
- * @param in1 The first vector
- * @param in2 the second vector
- * @return the cosine of the angle between the two vectors, which is a measure of similarity.
- */
- public static double findSimilarity(ArrayList<Double> in1, ArrayList<Double> in2) {
- //calculate dot product (in1[0]*in2[0] + in1[1]*in[1] ... in1[n]*in2[n])
- double dot = 0;
- //since when calculating we are only multiplying and adding same numbered indicies, we can stop at whatever length is the smallest
- for(int i = 0; i<in1.size() && i<in2.size(); i++) {
- dot += in1.get(i)*in2.get(i);
- }
- //calculate the magnitude of each (sqrt(in1[0]^2+in1[1]^2...in[n]^2))
- double squareofmagofin1 = 0;
- for(int i = 0; i < in1.size(); i++) {
- squareofmagofin1 += in1.get(i)*in1.get(i);
- }
- double squareofmagofin2 = 0;
- for(int i = 0; i < in1.size(); i++) {
- squareofmagofin2 += in2.get(i)*in2.get(i);
- }
- //calculate the square roots:
- double sqrtofmagofin2 = Math.sqrt(squareofmagofin2);
- double sqrtofmagofin1 = Math.sqrt(squareofmagofin2);
- /* Now doe this:
- * model the inputs as vectors, take cosine of both vectors as a measure of similarity
- * using item . args
- * cosx = _______________
- * ||item||||args||
- */
- double result = dot/(sqrtofmagofin1*sqrtofmagofin2);
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement