When you want to compute the average, there is a gotcha.
The common way to compute an average is to sum up all values and divide by the
number of values.
But here, we don’t store all those values, for two reasons.
The memory of the poor Arduino would overflow with all the numbers.
Also, summing up all the values would result in a big value, to big to represent
as an integer in Arduino code.
So, all we have is the last and the current value.
Luckily, there is a way to compute a running average from a few
values.
All that we need is the average so far and the new value of the random walk.
The new average is defined as
Lets transform this a bit to get
(a1 + … + an) / n+1 + an+1 / n+1
Multiplying the left term of the sum by n/n = 1 is ok and gives us
(((a1 + … + an) n) / n) / n+1 + an+1 / n+1
(a1 + … + an) / n + n / n+1 + an+1 / n+1
The left term is just our old average and so we finally get
new average = old_average + n / n+1 + an+1 / n+1
One nice aspect of this formula is that n / n+1 is getting closer to 1 as
n increases, so we don’t have big values in our computation.
Note: The formulas are a bit hard to read.
I would have liked to display the formulas using stem, but with my current
blogging process (convert Asciidoc to HTML and make a static website with
Pelican), this does not work.
Sorry for the inconvenience.