# Incremental averaging (different case)

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

• What is $m_{1.5}$ supposed to mean? $n$ have to be an integer in $m_n$. I think you are a confusing the number of the element with the value of the element. Dec 28, 2014 at 13:10
• Oh the problem I have to figure out is that let's say I bought apples several times. First 1.5kg for 3 dollars, second 2.5kg for 5 dollars, 1kg for 4 dollars. I need to calculate the average price per kg of apple incrementally. Dec 28, 2014 at 13:17
• Then you first have to calculate the price per kilo first: $P = [3/1.5, 5/2.5, 4/1.0] = [2,2,4]$ then do incremental averaging on this array. Dec 28, 2014 at 13:26
• Tried that way the answer comes wrong. It should be for A=[3] Q=[1.5] m=2,A=[3,5] Q=[1.5,2.5] m=2, A=[3,5,4] P=[1.5,2.5,1] m=2.4 Dec 28, 2014 at 13:29
• This is what I get: $m_1 = a_1 = 3/1.5 = 2.0$, $m_2 = m_1 + \frac{a_2-m_1}{2} = 2.0 + \frac{5/2.5-2.0}{2.0} = 2.0$, $m_3 = m_2 + \frac{a_3-m_2}{2} = 2.0 + \frac{4/1.0 - 2.0}{3.0} = 2.666$. What is wrong with this? Why do you think $2.4$ should be the correct result? Dec 28, 2014 at 13:34

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

• Ok it doesn't get any more accurate than this $$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}$$ Jan 14, 2015 at 8:17