# Is there a reliable recursive formula for a simple moving average (moving mean)?

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?

-
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 4:23
I program in Scala. –  Ivan Mar 16 '12 at 4:26

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}.$$

-
Yes, 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 4: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 4:54
This formula is not correct because it subtracts the new value rather than adds it! –  whuber Mar 16 '12 at 16:15
Yes, you was right. Just corrected it. –  chab Mar 17 '12 at 13:05
Thank you! (+1). I have taken the liberty of also correcting a slight indexing error. –  whuber Mar 17 '12 at 14:34