bug in the simple moving average calcualtion

A discussion forum for the JCommon class library.
Locked
Adnan Music

bug in the simple moving average calcualtion

Post by Adnan Music » Wed Jun 05, 2002 7:16 am

There is a bug in the simple moving average calcualtion (
method double[][] getMovingAverage(Number[] x_data, Number[] y_data, int period) in com.jrefinery.data.Statistics )

y values in the returned array are shifted (Y(n) is realy pair of X(n-1) and the array is one element shorter.
Here is the correct code (only two lines are changed, Old lines are commented out)

public static double[][] getMovingAverage(Number[] x_data, Number[] y_data, int period) {

// check arguments...
if(x_data.length != y_data.length) {
throw new IllegalArgumentException("Statistics.getMovingAverage(...)"
+": array lengths must be equal.");
}

if(period > x_data.length) {
throw new IllegalArgumentException("Statistics.getMovingAverage(...)"
+": period can't be longer than dataset.");
}

// Old double[][] result = new double[x_data.length - period][2];
double[][] result = new double[x_data.length - period + 1][2];
for(int i = 0; i < result.length; i++) {
// Old result[0] = x_data[i + period].doubleValue();
result[0] = x_data[i + period - 1].doubleValue();
// holds the moving average sum
double sum = 0.0;
for(int j = 0; j < period; j++) {
sum += y_data[i + j].doubleValue();
}
sum = sum/period;
result[1] = sum;
}
return result;

Locked