]> git.basschouten.com Git - openhab-addons.git/blob
08066bf9a843590af9fb1fc2c8928fed1879b0d3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.persistence.jdbc.internal.utils;
14
15 import java.math.BigDecimal;
16 import java.math.RoundingMode;
17 import java.util.LinkedList;
18 import java.util.Queue;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21
22 /**
23  * Calculates the average/mean of a number series.
24  *
25  * @author Helmut Lehmeyer - Initial contribution
26  */
27 @NonNullByDefault
28 public class MovingAverage {
29
30     private final Queue<BigDecimal> win = new LinkedList<>();
31     private final int period;
32     private BigDecimal sum = BigDecimal.ZERO;
33
34     public MovingAverage(int period) {
35         assert period > 0 : "Period must be a positive integer";
36         this.period = period;
37     }
38
39     public void add(Double num) {
40         add(new BigDecimal(num));
41     }
42
43     public void add(Long num) {
44         add(new BigDecimal(num));
45     }
46
47     public void add(Integer num) {
48         add(new BigDecimal(num));
49     }
50
51     public void add(BigDecimal num) {
52         sum = sum.add(num);
53         win.add(num);
54         if (win.size() > period) {
55             sum = sum.subtract(win.remove());
56         }
57     }
58
59     public BigDecimal getAverage() {
60         if (win.isEmpty()) {
61             return BigDecimal.ZERO; // technically the average is undefined
62         }
63         BigDecimal divisor = BigDecimal.valueOf(win.size());
64         return sum.divide(divisor, 2, RoundingMode.HALF_UP);
65     }
66
67     public double getAverageDouble() {
68         return getAverage().doubleValue();
69     }
70
71     public int getAverageInteger() {
72         return getAverage().intValue();
73     }
74 }