At one point in my life (namely college), I was really good at math. I breezed through calculus courses left and right and left discrete mathematics in my dust. Simple geometry was beneath me and looking back at the SATs, I laughed at how I struggled. A few years ago when I set out to go to graduate school, I had to take the GMAT and realized that my level of math understanding had regressed since I had graduated. I just couldn't figure out things that had been simple just a few years prior. Nowadays, I congratulate myself when I figure something out, thus my writing today.
I came across a need to create an algorithm that dynamically computed averages as new data came in. It would be inefficient to add up all the data each time a new datum appeared, so I wanted to have a rolling average calculation. I'm sure this has been solved before, but a few quick searches didn't turn up anything useful for me. What is this thing called? A rolling average? A dynamic average? A moving average? After pouring through all kinds of sites without any further idea I decided I'd try to figure it out myself. I do not claim to have created this technique, I only claim that for the first time in many years I figured out something mathematical without any outside help. I'm almost embarrassed by the simplicity of the solution but given that I don't do much complex math on a daily basis, I was still quite happy with myself.
Okay, how to recompute the average every time a new piece of data comes in:
- Take the previous average and multiply it by the previous number of data points (for instance, if you have 5 values and a new value just arrived, multiply the previous average by 5).
- Add the new value.
- Divide by the number of data points including the new one (if you have 5 values and a new value just arrived, then divide by 6).