0

Assuming I need to sample the average of the last $n$ elements in a sequence each time a new element is added to the sequence. Is there a way to get the new average without saving all the $n$ elements?

Alessio K
  • 10,599
  • When you say "the last $n$ elements", do you mean that $n$ is a constant completely unrelated to the actual number of elements of you sequence? For instance: that you are reading the ten-thousandth element, but you still only want the average of the last fifty elements? –  Aug 29 '20 at 23:07
  • yes - n is a constant completely unrelated to the actual number of the elements- which is basically going forever – Arik Malachi Aug 29 '20 at 23:11
  • If you have $a_1,a_2,\cdots ,a_M$ (with $M>n$) at some step, the average of the last $n$ elements is $$A_M=\dfrac{a_{M-n+1}+a_{M-n+2}+\cdots + a_M}n$$ and the new element is $a_{M+1}$, then the new average will be $$A_{M+1}=\dfrac{nA_M+a_{M+1}-a_{M-n+1}}n$$ assuming you have a way to find the $n^{th}$ element from the end of sequence at any time. All you need to update the average of the last $n$ elements are $3$ numbers, $(1)$ the last known average, $(2)$ the new element and $(3)$ the $n^{th}$ element from the end of the sequence. – Fawkes4494d3 Aug 29 '20 at 23:21
  • You may be right but this is not helping since I need to save all the elements to get the nth element. – Arik Malachi Aug 30 '20 at 06:23

0 Answers0