Aquí hay una manera.
public class Rolling {
private int size;
private double total = 0d;
private int index = 0;
private double samples[];
public Rolling(int size) {
this.size = size;
samples = new double[size];
for (int i = 0; i < size; i++) samples[i] = 0d;
}
public void add(double x) {
total -= samples[index];
samples[index] = x;
total += x;
if (++index == size) index = 0; // cheaper than modulus
}
public double getAverage() {
return total/size;
}
}
public class RollingTest extends TestCase {
private final static int SIZE = 5;
private static final double FULL_SUM = 12.5d;
private Rolling r;
public void setUp() {
r = new Rolling(SIZE);
}
public void testInitial() {
assertEquals(0d, r.getAverage());
}
public void testOne() {
r.add(3.5d);
assertEquals(3.5d/SIZE, r.getAverage());
}
public void testFillBuffer() {
fillBufferAndTest();
}
public void testForceOverWrite() {
fillBufferAndTest();
double newVal = SIZE + .5d;
r.add(newVal);
// get the 'full sum' from fillBufferAndTest(), add the value we just added,
// and subtract off the value we anticipate overwriting.
assertEquals((FULL_SUM + newVal - .5d)/SIZE, r.getAverage());
}
public void testManyValues() {
for (int i = 0; i < 1003; i++) r.add((double) i);
fillBufferAndTest();
}
private void fillBufferAndTest() {
// Don't write a zero value so we don't confuse an initialized
// buffer element with a data element.
for (int i = 0; i < SIZE; i++) r.add(i + .5d);
assertEquals(FULL_SUM/SIZE, r.getAverage());
}
}
Ya leyó http://en.wikipedia.org/wiki/Moving_average, especialmente "Media móvil ponderada" –
Una media móvil ponderada es mucho más simple de calcular, mucho más rápida y, en muchos casos, un valor más útil para calcular . es decir, se usa para modelar muchos sistemas. –