Mean and Standard Deviation

LA home
Computing
 Algorithms
 Bioinformatics
 FP,  λ
 Logic,  π
 MML
 Prog.Langs

Algorithms
 glossary
 Numerical
  Num'Errors
  Polynomials
  Stirling
  Mean&S.D.
  Integration

The mean, &mu, of N numbers, A[1], ..., A[N], is their sum divided by N, i.e. (∑1..N A[i])/N. Their variance is (∑1..N (A[i]-μ)2)/N and their standard deviation, σ, is sqrt(variance); note that these quantities are always >=0. The mean gives the "centre of gravity" (CG) of the numbers, and the standard deviation indicates how far they stray from the CG, on average.

Both the mean and the standard deviation can be calculated on a single scan through A[ ] even though the mean is not known until the end of the scan:

variance
= σ2 
= ( ∑i=1..N (A[i]-μ)2 ) / N
= ( (∑ A[i]2) - 2*μ*(∑ A[i]) + N*μ2 ) / N
= ( (∑ A[i]2) - 2*μ*sum ) / N + μ2
= ( ∑i=1..N A[i]2 ) / N - μ2
i.e. the mean squares minus the squared mean.
Hence σ = sqrt(sumSq / N - μ2)
where sumSq = ∑1..N A[i]2

This gives the following algorithm:

  sum := 0.0;
sumSq := 0.0;

for i in {1 .. N} do
     sum +:= A[i];
   sumSq +:= A[i]2
end for;

  mean := sum / N;
stdDev := sqrt(sumSq / N - mean2);

inp[]
opt=
-- L.A., 1999

Notes

window on the wide world:

Computer Science Education Week

Linux
 Ubuntu
free op. sys.
OpenOffice
free office suite,
ver 3.4+

The GIMP
~ free photoshop
Firefox
web browser
FlashBlock
like it says!

© L. Allison   http://www.allisons.org/ll/   (or as otherwise indicated),
Faculty of Information Technology (Clayton), Monash University, Australia 3800 (6/'05 was School of Computer Science and Software Engineering, Fac. Info. Tech., Monash University,
was Department of Computer Science, Fac. Comp. & Info. Tech., '89 was Department of Computer Science, Fac. Sci., '68-'71 was Department of Information Science, Fac. Sci.)
Created with "vi (Linux + Solaris)",  charset=iso-8859-1,  fetched Thursday, 24-Apr-2014 23:09:53 EST.