sums and should be zero, but the second pass compensates for any small error. Online A stable one-pass algorithm exists, similar to the online algorithm for computing the variance, that computes co-moment : The apparent asymmetry in that last equation is due to the fact that , so both update terms are equal to . Even greater accuracy can be achieved by first computing the means, then using the stable one-pass algorithm on the residuals. Thus the covariance can be computed as def online_covariance(data1, data2): meanx = meany = C = n = 0 for x, y in zip(data1, data2): n += 1 dx = x - meanx meanx += dx / n meany += (y - meany) / n C += dx * (y - meany) population_covar = C / n # Bessel's correction for sample variance sample_covar = C / (n - 1) A small modification can also be made to compute the weighted covariance: def online_weighted_covariance(data1, data2, data3): meanx = meany = 0 wsum = wsum2 = 0 C = 0 for x, y, w in zip(data1, data2, data3): wsum += w wsum2 += w * w dx = x - meanx meanx += (w / wsum) * dx meany += (w / wsum) * (y - meany) C += w * dx * (y - meany) population_covar = C / wsum # Bessel's correction for sample variance # Frequency weights sample_frequency_covar = C / (wsum - 1) # Reliability weights sample_reliability_covar = C / (wsum - wsum2 / wsum) Likewise, there is a formula for combining the covariances of two sets that can be used to parallelize the computation: Weighted batched version A version of the weighted online algorithm that does batched updated also exists: let denote the weights, and write The covariance can then be computed as See also Kahan summation algorithm Squared deviations from the mean Yamartino method References External links Statistical algorithms Statistical deviation and dispersion Articles with example pseudocode Articles with example Python (programming language) code