Skip to content

Instantly share code, notes, and snippets.

@digitalex
Created November 20, 2012 09:28
Show Gist options
  • Save digitalex/4116951 to your computer and use it in GitHub Desktop.
Save digitalex/4116951 to your computer and use it in GitHub Desktop.
Moving average over a fixed window size, constant-time operations.
/**
* 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