Is there a function in java to get moving average

后端 未结 7 1827
囚心锁ツ
囚心锁ツ 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条回答
  •  臣服心动
    2020-12-14 16:52

    Here's a good implementation, using BigDecimal:

    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class MovingAverage {
    
        private final Queue window = new LinkedList();
        private final int period;
        private BigDecimal sum = BigDecimal.ZERO;
    
        public MovingAverage(int period) {
            assert period > 0 : "Period must be a positive integer";
            this.period = period;
        }
    
        public void add(BigDecimal num) {
            sum = sum.add(num);
            window.add(num);
            if (window.size() > period) {
                sum = sum.subtract(window.remove());
            }
        }
    
        public BigDecimal getAverage() {
            if (window.isEmpty()) return BigDecimal.ZERO; // technically the average is undefined
            BigDecimal divisor = BigDecimal.valueOf(window.size());
            return sum.divide(divisor, 2, RoundingMode.HALF_UP);
        }
    }
    

提交回复
热议问题