Is there a function in java to get moving average

后端 未结 7 1811
囚心锁ツ
囚心锁ツ 2020-12-14 16:14

I have a situation where I need to process 5000 samples from a device in every 0.5 sec.

Lets say the window size is 100, then there would be 50 points resulting fro

7条回答
  •  -上瘾入骨i
    2020-12-14 16:50

    Here's one way.

    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());
        }
    }
    

提交回复
热议问题