-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVecOps.java
66 lines (56 loc) · 2 KB
/
VecOps.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package s6regen;
public class VecOps {
final static float MIN_SQ = 1e-20f;
public static void multiply(float[] rVec, float[] x, float[] y) {
for (int i = 0; i < rVec.length; i++) {
rVec[i] = x[i] * y[i];
}
}
public static void multiplyAddTo(float[] rVec, float[] x, float[] y) {
for (int i = 0; i < rVec.length; i++) {
rVec[i] += x[i] * y[i];
}
}
// x-y
public static void subtract(float[] rVec, float[] x, float[] y) {
for (int i = 0; i < rVec.length; i++) {
rVec[i] = x[i] - y[i];
}
}
public static void add(float[] rVec, float[] x, float[] y) {
for (int i = 0; i < rVec.length; i++) {
rVec[i] = x[i] + y[i];
}
}
public static void scale(float[] rVec, float[] x, float s) {
for (int i = 0; i < rVec.length; i++) {
rVec[i] = x[i] * s;
}
}
// reduce the magnitude by t, if the magnitude is reduced below 0 it is made 0.
// with t=1, 1.5 becomes 0.5, -2.5 becomes -1.5, .9 becomes 0 etc.
public static void truncate(float[] rVec, float[] x, float t) {
for (int i = 0; i < rVec.length; i++) {
int f = Float.floatToRawIntBits(x[i]);
int s = f & 0x80000000; // get sign bit
float m = Float.intBitsToFloat(f & 0x7fffffff) - t; //abs(x[i])-t
if (m < 0f) {
m = 0f;
}
rVec[i] = Float.intBitsToFloat(Float.floatToRawIntBits(m) | s); // put sign back in
}
}
public static float sumSq(float[] vec) {
float sum = 0f;
for (int i = 0; i < vec.length; i++) {
sum += vec[i] * vec[i];
}
return sum;
}
// Assuming each elememt of is from a Gaussian distribution of zero mean
// adjust the variance of each element to 1.
public static void adjust(float[] rVec, float[] x) {
float adj = 1f / (float) Math.sqrt((sumSq(x) / x.length) + MIN_SQ);
scale(rVec, x, adj);
}
}