Tell me more ×
Cross Validated is a question and answer site for statisticians, data analysts, data miners and data visualization experts. It's 100% free, no registration required.

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?

share|improve this question
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

2 Answers

up vote 6 down vote accepted

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

share|improve this answer
1  
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
1  
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
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.

share|improve this answer
This is a way of updating a cumulative mean but not a moving mean: that's why no buffer is needed. – whuber Feb 4 at 13:53

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.