Created
November 20, 2012 09:28
-
-
Save digitalex/4116951 to your computer and use it in GitHub Desktop.
Moving average over a fixed window size, constant-time operations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Calculates average over the last X data points. | |
* | |
* All operations are constant time (O(1)). | |
* | |
* Note the possibility of overflow, if the sum | |
* of the last X data points exceeds Float.MAX_VALUE. | |
*/ | |
class MovingAverage { | |
private final int maxSize | |
private float sum = 0.0f | |
private LinkedList<Float> data = new LinkedList<Float>() | |
MovingAverage(int maxSize = 10) { | |
this.maxSize = maxSize | |
} | |
float add(float x) { | |
data.addLast(x) | |
sum += x | |
if (n > maxSize) { | |
sum -= data.removeFirst() | |
} | |
average | |
} | |
float getAverage() { | |
sum / n | |
} | |
int getN() { | |
data.size() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment