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