How to calculate moving average without keeping the count and data-total?
Here's a simple and efficient way to calculate the moving average of a stream of data without keeping track of the count or the data-total:
double approxRollingAverage (double avg, double new_sample) {
avg -= avg / N;
avg += new_sample / N;
return avg;
}
In this code:
avg
is the current moving average.new_sample
is the new data point to be added to the moving average.N
is the number of samples over which the moving average is calculated.
To use this function, simply call it with the current moving average and the new data point. The function will return the updated moving average.
For example, the following code calculates the moving average of the numbers 1, 2, 3, 4, and 5:
double avg = 0;
for (int i = 1; i <= 5; i++) {
avg = approxRollingAverage(avg, i);
System.out.println(avg);
}
This code will print the following output:
1.0
1.5
2.0
2.5
3.0
As you can see, the moving average starts at 1 and gradually increases as new data points are added.
This method is known as the "Welford's algorithm" and it is a very efficient way to calculate the moving average of a stream of data.