# incremental computation of standard deviation

How can I compute the standard deviation in an incremental way (using the new value and the last computed mean and/or std deviation) ?

for the non incremental way, I just do something like:
$$SN=√1NN∑i=1(xi−¯x)2.S_N=\sqrt{\frac1N\sum_{i=1}^N(x_i-\overline{x})^2}.$$

mean = Mean(list)
for i = 0 to list.size
stdev = stdev + (list[i] - mean)^2
stdev = sqrRoot( stdev / list.size )


I think the easiest way to do this is with an orthogonality trick. I’ll show how to incrementally compute the variance instead of the standard deviation. Let $$X1,X2,...X_1, X_2, ...$$ be an iid sequence of random variables with $$ˉX=n−1∑nj=1Xj\bar X = n^{-1} \sum_{j = 1} ^ n X_j$$ and $$s2ns^2_n$$ defined similarly as the $$nn$$‘th sample variance (I use a denominator of $$n−1n-1$$ instead of $$nn$$ in your picture to keep things unbiased for the variance, but you can use the same argument just adding $$11$$ to all the terms with $$nn$$ in them). First write
$$s2n=∑nj=1(Xj−ˉXn)2n−1=∑nj=1(Xj−ˉXn−1+ˉXn−1−ˉXn)2n−1. s^2_n = \frac{\sum_{j = 1} ^ n (X_j - \bar X_n)^2}{n - 1} = \frac{\sum_{j = 1} ^ n (X_j - \bar X_{n - 1} + \bar X_{n - 1} - \bar X_n)^2}{n - 1}.$$
Expand this to get $$s2n=(n−2)s2n−1+(n−1)(ˉXn−1−ˉXn)2+2∑n−1j=1(Xj−ˉXn−1)(ˉXn−1−ˉXn)+(Xn−ˉXn)2n−1 s^2_n = \frac{(n - 2)s^2_{n - 1} + (n - 1) (\bar X_{n - 1} - \bar X_n)^2 + 2 \sum_{j = 1} ^ {n - 1} (X_j - \bar X_{n - 1})(\bar X_{n - 1} - \bar X_n) + (X_n - \bar X_{n})^2}{n - 1}$$
and it is easy to show that the summation term above is equal to $$00$$ which gives $$s2n=(n−2)s2n−1+(n−1)(ˉXn−1−ˉXn)2+(Xn−ˉXn)2n−1. s^2_n = \frac{(n - 2)s^2_{n - 1} + (n - 1)(\bar X_{n - 1} - \bar X_n)^2 + (X_n - \bar X_{n})^2}{n - 1}.$$
EDIT: I assumed you already have an incremental expression for the sample mean. It is much easier to get that: $$ˉXn=n−1[Xn+(n−1)ˉXn−1]\bar X_n = n^{-1}[X_n + (n-1)\bar X_{n-1}]$$.