I come up with this
n=1;
curAvg = 0;
loop{
curAvg = curAvg + (newNum - curAvg)/n;
n++;
}
I think highlights of this way are:
- It avoids big numbers (and possible overflow if you would sum and then divide)
- you save one register (not need to store sum)
The trouble might be with summing error - but I assume that generally there shall be balanced numbers of round up and round down so the error shall not sum up dramatically.
Do you see any pitfalls in this solution? Have you any better proposal?
1 2
and3
next, you'd docurAvg = 1.5 + (3 - 1.5)/2 = 1.5 + 0.75 = 2.25
, which would be wrong? – IVladnew average = old average + (next data - old average) / next count
– Donald_WcurAvg = 1.5+(3-1.5)/3=1.5+0.5 = 2
, which is correct. – Natesh Raina