To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.

Statistics Download as Zip
| Branch: | Revision:

root / src / may / bits / VectorBits.java @ 595:3b1f2aa8d36b

History | View | Annotate | Download (1.55 KB)

1

    
2
package may.bits;
3

    
4
public class VectorBits
5
{
6
    public static void checkLengths(double[] v1, double[] v2) {
7
        if (v1.length != v2.length) {
8
            IllegalArgumentException e = new IllegalArgumentException
9
                ("Found vector of length " + v2.length +
10
                 ", but all so far in this arithmetic operation have had length " +
11
                 v1.length);
12
            throw e;
13
        }
14
    }
15

    
16
    public static double sum(double[] v) {
17
        double tot = 0.0;
18
        int len = v.length;
19
        for (int i = 0; i < len; ++i) {
20
            tot += v[i];
21
        }
22
        return tot;
23
    }
24

    
25
    public static void multiplyBy(double[] out, double[] in) {
26
        checkLengths(out, in);
27
        for (int i = 0; i < in.length; ++i) {
28
            out[i] *= in[i];
29
        }
30
    }
31

    
32
    public static void divideBy(double[] out, double[] in) {
33
        checkLengths(out, in);
34
        for (int i = 0; i < in.length; ++i) {
35
            out[i] /= in[i];
36
        }
37
    }
38

    
39
    public static void addTo(double[] out, double[] in) {
40
        checkLengths(out, in);
41
        for (int i = 0; i < in.length; ++i) {
42
            out[i] += in[i];
43
        }
44
    }
45

    
46
    public static void subtractFrom(double[] out, double[] in) {
47
        checkLengths(out, in);
48
        for (int i = 0; i < in.length; ++i) {
49
            out[i] -= in[i];
50
        }
51
    }
52

    
53
    public static double[] scaled(double[] v, double factor) {
54
        int len = v.length;
55
        double[] out = new double[v.length];
56
        for (int i = 0; i < len; ++i) {
57
            out[i] = v[i] * factor;
58
        }
59
        return out;
60
    }
61
    
62
    public static double euclideanDistance(double[] v1, double[] v2) {
63
        checkLengths(v1, v2);
64
        double sum = 0.0;
65
        for (int i = 0; i < v1.length; ++i) {
66
            double d = v1[i] - v2[i];
67
            sum += d * d;
68
        }
69
        return Math.sqrt(sum);
70
    }
71
}
72