the given data # use (n-1) if data are samples of a larger population return variance This formula also facilitates the incremental computation that can be expressed as K = Ex = Ex2 = 0.0 n = 0 def add_variable(x): global K, n, Ex, Ex2 if n == 0: K = x n += 1 Ex += x - K Ex2 += (x - K) ** 2 def remove_variable(x): global K, n, Ex, Ex2 n -= 1 Ex -= x - K Ex2 -= (x - K) ** 2 def get_mean(): global K, n, Ex return K + Ex / n def get_variance(): global n, Ex, Ex2 return (Ex2 - Ex**2 / n) / (n - 1) Two-pass algorithm An alternative approach, using a different formula for the variance, first computes the sample mean, and then computes the sum of the squares of the differences from the mean, where s is the standard deviation. This is given by the following code: def two_pass_variance(data): n = len(data) mean = sum(data) / n variance = sum([(x - mean) ** 2 for x in data]) / (n - 1) return variance This algorithm is numerically stable if n is small. However, the results of both of these simple algorithms ("naïve" and "two-pass") can depend inordinately on the ordering of the data and can give poor results for very large data sets due to repeated roundoff error in the accumulation of the sums. Techniques such as compensated summation can be used to combat this error to a degree. Welford's online algorithm It is often useful to be able to compute the variance in a single pass, inspecting each value only once; for example, when the data is being collected without enough storage to keep all the values, or when costs of memory access dominate those of computation. For such an online algorithm, a recurrence relation is required between quantities from which the required statistics can be calculated in a numerically stable fashion. The following formulas can be used to update the mean and (estimated) variance of the sequence, for an additional element xn. Here, denotes the sample mean of the first n samples , their biased sample variance, and their unbiased sample variance. These formulas suffer from numerical instability, as they repeatedly subtract a small number from a big number which scales with n. A better quantity for updating is the sum of squares