Skip to content
DeepForgeby svx
All problems

Running Stats Update

Problem

Update running mean and sum of squared deviations with one observation using Welford's method.

Given mean, m2, and count before the observation, return [new_mean, new_m2, count + 1], where new_mean = mean + delta / (count + 1) and new_m2 = m2 + delta * (x - new_mean) with delta = x - mean.

Hint

m2 divided by count gives the population variance without a second pass.

Test cases

case 1
in: [0,0,0,5]
expected: [5,0,1]
case 2
in: [5,0,1,3]
expected: [4,2,2]
case 3
in: [4,2,2,7]
expected: [5,8,3]
case 4
in: [1,2,2,1]
expected: [1,2,3]
Starter codePython
def running_stats_update(mean, m2, count, x):
    # Your code here
    pass

4 test cases · run your code against them in the editor