Incremental averaging (different case)

341 Views Asked by At

I've seen the integer version $$m_n = m_{n-1} + \frac{a_n-m_{n-1}}{n}.$$ But how do I calculate it where there are amounts, which is $$A=[3, 5, 4]$$ and the corresponding quantities $$Q=[1.5, 2.5, 1]$$ Below version doesn't work, I'm doing it like this $$m_{1.5}=0+\frac{3-0}{1.5}=2$$ $$m_{4}=2+\frac{5-2}{4}=2.75$$ Which is wrong $m_4$ should have been $$\frac{3+5}{1.5+2.5}=2$$

In this case, do I calculate the average incrementally in correct way?

Example for clarification First I bought 1.5kg apple for 3 dollars, then 2.5kg for 5 dollars, then 1kg for 4 dollars. I need to calculate the average price per kg of apple incrementally

Please read the comments below

1

There are 1 best solutions below

1
On BEST ANSWER

Well, it's quite easy: let $a_i$ be the prices and $q_i$ the respective quantities. Let $A_n = a_1 +a_2 + \cdots a_n$ , $Q_n = q_1 +q_2 + \cdots q_n$

Then the average price is

$$M_n = \frac{A_n}{Q_n}=\frac{A_{n-1}+a_n}{Q_{n-1}+q_n}=\frac{Q_{n-1} M_{n-1} +a_n }{Q_{n-1}+q_n}$$

You cannot obtain the recursion in terms of $M_{n-1}$ (and $n$) alone, you need to store $Q_{n-1}$ (instead of $n$; indeed, you can think of it as a "effective" $n$).

In the particular case in which $q_n=k$ (constant), then $Q_n= n k$ and

$$M_n= \frac{ (n-1) k M_{n-1} +a_n}{k n}=M_{k-1} + \frac{a_n/k-M_{n-1}}{ n}$$