view src/may/bits/VectorBits.java @ 561:c5afeb185539

Fixes to vector sizing in resampler
author Chris Cannam
date Wed, 30 Apr 2014 13:32:14 +0100
parents 3fdffd2d0649
children 495cc8973458
line wrap: on
line source

package may.bits;

public class VectorBits
{
    public static void checkLengths(double[] v1, double[] v2) {
	if (v1.length != v2.length) {
	    IllegalArgumentException e = new IllegalArgumentException
		("Found vector of length " + v2.length +
		 ", but all so far in this arithmetic operation have had length " +
		 v1.length);
//	    e.printStackTrace();
	    throw e;
	}
    }

    public static double sum(double[] v) {
	double tot = 0.0;
	int len = v.length;
	for (int i = 0; i < len; ++i) {
	    tot += v[i];
	}
	return tot;
    }

    public static void multiplyBy(double[] out, double[] in) {
	checkLengths(out, in);
	for (int i = 0; i < in.length && i < out.length; ++i) {
	    out[i] *= in[i];
	}
	for (int i = in.length; i < out.length; ++i) {
	    out[i] *= 0.0;
	}
    }

    public static void divideBy(double[] out, double[] in) {
	checkLengths(out, in);
	for (int i = 0; i < in.length && i < out.length; ++i) {
	    out[i] /= in[i];
	}
    }

    public static void addTo(double[] out, double[] in) {
	checkLengths(out, in);
	for (int i = 0; i < in.length && i < out.length; ++i) {
	    out[i] += in[i];
	}
    }

    public static void subtractFrom(double[] out, double[] in) {
	checkLengths(out, in);
	for (int i = 0; i < in.length && i < out.length; ++i) {
	    out[i] -= in[i];
	}
    }

    public static double[] scaled(double[] v, double factor) {
	int len = v.length;
	double[] out = new double[v.length];
	for (int i = 0; i < len; ++i) {
	    out[i] = v[i] * factor;
	}
	return out;
    }
}