Loading problem...
In many real-world applications, data arrives continuously as a stream, and we need to maintain statistical summaries without storing every data point. One of the most essential streaming statistics is the running average (also known as the online mean or incremental mean).
Consider a scenario where you're monitoring sensor readings, user engagement metrics, or reward signals in a reinforcement learning agent. Storing millions or billions of historical observations is often impractical due to memory constraints. Instead, we can maintain an accurate running average using only three pieces of information:
The Incremental Update Formula:
When a new observation arrives, the updated mean can be computed using:
$$Q_{new} = Q_{old} + \frac{1}{n} \cdot (x - Q_{old})$$
This elegant formula has an intuitive interpretation: we adjust the old estimate toward the new value by a fraction that decreases as more samples are accumulated. Early observations have more influence on the estimate, while later observations make smaller adjustments—exactly the behavior we'd expect from a proper averaging process.
Why This Formula Works:
The term (x - Q_old) represents the prediction error—how far the new observation deviates from our current estimate. We then scale this error by 1/n to determine the appropriate adjustment. This is mathematically equivalent to recomputing the mean from scratch, but requires O(1) space and O(1) time per update instead of O(n) for both.
Your Task: Write a function that computes the updated running average given:
Return the updated mean after incorporating the new observation.
previous_mean = 2.0
sample_count = 2
new_value = 6.04.0With a previous mean of 2.0 and this being the 2nd observation, we apply the incremental formula:
Q_new = Q_old + (1/n) × (x - Q_old) Q_new = 2.0 + (1/2) × (6.0 - 2.0) Q_new = 2.0 + 0.5 × 4.0 Q_new = 2.0 + 2.0 = 4.0
This means if the first value was 2.0 and the second is 6.0, the average is indeed (2.0 + 6.0) / 2 = 4.0.
previous_mean = 0.0
sample_count = 1
new_value = 5.05.0When sample_count is 1, this is the very first observation. The previous mean of 0.0 represents the initial state (no data yet).
Q_new = 0.0 + (1/1) × (5.0 - 0.0) Q_new = 0.0 + 1.0 × 5.0 Q_new = 5.0
The first observation becomes the entire mean, as expected.
previous_mean = 10.0
sample_count = 3
new_value = 10.010.0When the new observation equals the current mean, no adjustment is needed:
Q_new = 10.0 + (1/3) × (10.0 - 10.0) Q_new = 10.0 + (1/3) × 0.0 Q_new = 10.0
The error term is zero, so the mean remains unchanged. This demonstrates that the formula correctly handles observations that match the current estimate.
Constraints