# How can I incrementally calculate the 4 central moments in statistics (mean, standard deviation, skewness and curtosis) when a value is removed?

I'm incrementally calculating the 4 central moments. When a value x is added and n, M1, M2, M3 and M4 are some predefined values, I'm using the following algorithm:

n1 = n
n = n + 1
delta = x - mean
delta_n = delta / n
delta_n2 = delta_n * delta_n
term1 = delta * delta_n * n1
mean = mean + delta_n
M4 = M4 + term1 * delta_n2 * (n*n - 3*n + 3) + 6 * delta_n2 * M2 - 4 * delta_n * M3
M3 = M3 + term1 * delta_n * (n - 2) - 3 * delta_n * M2
M2 = M2 + term1


This one works, but now I'm wondering if there exists a similar method when a value is removed or if I can just turn this one around? For the first and second moment it works if I just switch the '-' with the '+' signs. However, for the third and third moment I get a wrong number. Currently I did this where x is the new value added:

n1 = n
n = n - 1
delta = x - mean
delta_n = delta / n
delta_n2 = delta_n * delta_n
term1 = delta * delta_n * n1
mean = mean - delta_n
M4 = M4 - term1 * delta_n2 * (n*n - 3*n + 3) - 6 * delta_n2 * M2 + 4 * delta_n * M3
M3 = M3 - term1 * delta_n * (n - 2) + 3 * delta_n * M2
M2 = M2 - term1


Do I have a mistake there or does this method just don't work for the third and fourth moment of statistics? Is there another method?

• Note also that your code contains underscores, which are restricted to pattern matching in MMA, and would not work as posted. Were you using some other formatting in your notebook instead (e.g. subscripts)?
– MarcoB
Apr 24, 2020 at 15:26
• You're right I moved the question to math.stackexchange.com. Apr 24, 2020 at 15:43
• The first central moment is always zero, so that's trivial to update. Apr 24, 2020 at 15:59