Say, if I had a final array of numbers, say:
{1, 5, 7, 2}
the average for them will be:
(1 + 5 + 7 + 2) / 4; //Or, sum of all elements, divided by their number
But what if my array is constantly growing and I need to know the current average number at an instance of time when the full array is not known yet. How do you calculate that?
Say, like when I'm trying to display current data transfer rate.
Every time you get a new value update your sum and count and simply divide the two when you need to display them to the user.
For data transfer rate this is problematic approach though. Think of the scenario where you start a transfer with high bandwidth and then the connection drops, with a simple average it could take a long time for your UI to reflect that the current transfer rate is 0. Using a weighted moving average is a quick way to make your UI seem more responsive.
The simplest implementation of this is to sample the transfer rate periodically (say every 5 seconds) and calculate your rate with something like:
float weight = 2.0; //you are going to want to tweak this to get the right balance between "responsive" and "noisy"
void UpdateAverage(float newValue)
{
this.Average = (this.Average + (newValue*weight))/(weight+1)
}