How to Calculate an Average Without Storing Values
uptimesniper.com
uptimesniper.com
On some systems, that multiplication and division also may be slow.
Even if it is stable, I think it’s better to keep track of the running sum and the number of items seen:
sumSoFar += newItem
numSeen += 1
and only do the division when you need the average.The risk then is overflow for large numbers of items, but that’s no worse than the proposed algorithm. Its running value will not overflow as easily, but the intermediate value of the multiplication can do just as easily.