Maintaining a Running Average
A running average can keep a sum and an observation count rather than retaining every input.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Update both quantities
After reading 2 and 8, the sum is ten and the count is two, giving five. After adding 20, the sum is thirty and the count is three, giving ten. Taking the mean of five and twenty would yield 12.5 because it gives the earlier average the weight of a single observation.
Handle inputs with no readings
Before any observation, a result can be explicitly absent. If missing readings are ignored, both the accumulator and counter should skip them under the same condition.[1]
Keep the sum and count together
If observations arrive as 4, 6, and 20, the first two average five. Combining five with twenty by taking their average gives 12.5, whereas the correct average after all three is ten. The earlier mean describes two observations. Retaining sum ten and count two allows adding the new value and incrementing the count. Weighted and unweighted means explains how these summaries combine.
Specify which observations the denominator includes
If a sensor can produce an explicit absent value, skipping it should leave both the sum and observed count unchanged. A real zero still increments that count. From 4, absent, and 0, the observed mean is two. Filling the absent slot with zero would instead give \(4/3\) under that substitution policy.
Test a first real zero and a collection with no valid observations. A no-observation mean needs a useful result defined by the caller's interface. If the numeric scale is large or many values are processed, also consider the precision of the retained sum. See binary floating-point rounding.