Moving Average

统计学的一个方法, 多用在股票上, 不过我不炒股, 我不知道这个东西学名叫什么.

给一个streaming data, 让你找到最近出现的k个元素的平均数. 我看到网上好多人用doubly queue. 感觉没必要, 可以用个fixed size array. 然后需要注意的是窗口展开的时候, 要特殊照顾一下. 当遇到k+1元素的时候, avg(k+1) = (item(k+1) + avg(k)*k)/(k+1).

public class MovingAverage {
    private float avg;
    private int windowsSize;
    private float[] samples;
    private int index = 0;
    private int k = 0;
    public MovingAverage(int k){
        this.windowsSize = 0;
        this.k = k;
        samples = new float[k];
    }

    public void add(float val) {
        float pre = samples[index];
        samples[index] = val;
        if (windowsSize < k){
            avg = avg * ((float)windowsSize) / ((float)windowsSize+1);
            windowsSize++;
        }
        avg = avg + (val  - pre) / windowsSize;
        index = (index+1) % k;
    }

    public float getAvg(){return avg;}


    public static void main(String[] args) {
        MovingAverage average = new MovingAverage(2);
        average.add(5);
        average.add(11);
        average.add(3);
        average.add(3);
        average.add(3);
        average.add(3);
        average.add(3);
        System.out.println(average.getAvg());
    }
}