Advertisement
Guest User

Untitled

a guest
Mar 24th, 2013
431
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. /**
  2.      * this method finds the vector similarity between two arrays between 0 and 1
  3.      * where 1 is the highest value of similarity
  4.      * returns to within a margin of error because even double precision floats
  5.      * in java are not perfect.
  6.      * @param in1 The first vector
  7.      * @param in2 the second vector
  8.      * @return the cosine of the angle between the two vectors, which is a measure of similarity.
  9.      */
  10.     public static double findSimilarity(ArrayList<Double> in1, ArrayList<Double> in2) {
  11.         //calculate dot product (in1[0]*in2[0] + in1[1]*in[1] ... in1[n]*in2[n])
  12.         double dot = 0;
  13.         //since when calculating we are only multiplying and adding same numbered indicies, we can stop at whatever length is the smallest
  14.         for(int i = 0; i<in1.size() && i<in2.size(); i++) {
  15.             dot += in1.get(i)*in2.get(i);
  16.         }
  17.        
  18.         //calculate the magnitude of each (sqrt(in1[0]^2+in1[1]^2...in[n]^2))
  19.         double squareofmagofin1 = 0;
  20.         for(int i = 0; i < in1.size(); i++) {
  21.             squareofmagofin1 += in1.get(i)*in1.get(i);
  22.         }
  23.        
  24.         double squareofmagofin2 = 0;
  25.         for(int i = 0; i < in1.size(); i++) {
  26.             squareofmagofin2 += in2.get(i)*in2.get(i);
  27.         }
  28.        
  29.         //calculate the square roots:
  30.         double sqrtofmagofin2 = Math.sqrt(squareofmagofin2);
  31.         double sqrtofmagofin1 = Math.sqrt(squareofmagofin2);
  32.        
  33.         /* Now doe this:
  34.          * model the inputs as vectors, take cosine of both vectors as a measure of similarity
  35.          * using   item . args
  36.          * cosx = _______________
  37.          *       ||item||||args||
  38.          */
  39.        
  40.         double result = dot/(sqrtofmagofin1*sqrtofmagofin2);
  41.         return result;      
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement