View Javadoc

1   
2   package net.sf.classifier4J.vector;
3   
4   
5   public class VectorUtils {
6       public static int scalarProduct(int[] one, int[] two) throws IllegalArgumentException {
7           if ((one == null) || (two == null)) {
8               throw new IllegalArgumentException("Arguments cannot be null");
9           }
10          
11          if (one.length != two.length) {
12              throw new IllegalArgumentException("Arguments of different length are not allowed");
13          }
14          
15          int result = 0;
16          for (int i = 0; i < one.length; i++) {
17              result += one[i] * two[i];
18          }
19          return result;
20      }
21      
22      public static double vectorLength(int[] vector) throws IllegalArgumentException {
23          if (vector == null) {
24              throw new IllegalArgumentException("Arguments cannot be null");
25          }
26          
27          double sumOfSquares = 0d;
28          for (int i = 0; i < vector.length; i++) {
29              sumOfSquares = sumOfSquares + (vector[i] * vector[i]);
30          }
31          
32          return Math.sqrt(sumOfSquares);
33      }
34      
35      public static double cosineOfVectors(int[] one, int[] two) throws IllegalArgumentException {
36          if ((one == null) || (two == null)) {
37              throw new IllegalArgumentException("Arguments cannot be null");
38          }
39          
40          if (one.length != two.length) {
41              throw new IllegalArgumentException("Arguments of different length are not allowed");
42          }     
43          double denominater = (vectorLength(one) * vectorLength(two));
44          if (denominater == 0) {
45              return 0;
46          } else {
47              return (scalarProduct(one, two)/denominater);
48          }
49      }
50  }