I've tried some recursive moving average formulae (to reuse a previous output instead of summing the whole n-long set for every i) I've managed to find but none of them produces the same results as a bare moving mean does. Is there a reliable recursive formula which would produce exactly (or almost exactly) the same output as a bare moving mean?
Asked
Active
Viewed 1.1k times
6
Ivan
- 173
-
It seems that you are using some kind of software. If this is true, please tell us, it is easier to give an answer then. – mpiktas Mar 16 '12 at 04:23
-
I program in Scala. – Ivan Mar 16 '12 at 04:26
2 Answers
8
Just try to remove the last value of the window and add the new one.
If
$$MA(t)=\frac{1}{w}\sum\limits_{i=t-w+1}^t{y_i}$$
then
$$MA(t+1)=MA(t)+\frac{y(t+1)-y(t-w+1)}{w}.$$
-
1Yes, this formula looks reasonable but somehow the result I get is always below the non-recursive moving mean. And the difference looks constant. Perhaps I have a bug in my code, the difference would hardly be constant otherwise. – Ivan Mar 16 '12 at 04:37
-
The possible reason might be the following. If the values of y(t) are relatively small and w is big, divisions for sum(y(t))/w and (y(t)+y(t-w))/w have different precision orders. (for example if y(t) is approximately 0.001, and n is 10000, division 0.001/10000 is less accurate, compared to 10/10000). Then if you add real numbers with different precisions, the smaller one is truncated. – chab Mar 16 '12 at 04:54
-
This formula is not correct because it subtracts the new value rather than adds it! – whuber Mar 16 '12 at 16:15
-
1
-
Thank you! (+1). I have taken the liberty of also correcting a slight indexing error. – whuber Mar 17 '12 at 14:34
1
double mean(const double F, const double C, unsigned int *n)
{
return (F*(*n)+C)/(++*n);
}
F is the old average number, C is a new addition to the avarage. *n is the number of values in F. This does not need a buffer.
-
This is a way of updating a cumulative mean but not a moving mean: that's why no buffer is needed. – whuber Feb 04 '13 at 13:53