16 lines
676 B
Plaintext
16 lines
676 B
Plaintext
// Variance: the sample variance (dividing by N - 1), in two passes: the mean
|
|
// first, then the squared distances from it. The one-pass formula
|
|
// (SUM X^2 - N * MEAN^2) / (N - 1) subtracts two nearly equal large numbers
|
|
// and loses every digit when the values sit far from 0: on the third case it
|
|
// gives -170.66666666666666 in FLOAT arithmetic, where the two passes give 30.0.
|
|
USE stats.Mean
|
|
FUNCTION Variance(X : LIST OF FLOAT) RETURNS FLOAT
|
|
REQUIRE LENGTH(X) >= 2
|
|
DECLARE M : FLOAT <- Mean(X)
|
|
DECLARE Total : FLOAT <- 0.0
|
|
FOR I <- 0 TO LENGTH(X)
|
|
Total <- Total + (X[I] - M) * (X[I] - M)
|
|
NEXT I
|
|
RETURN Total / (LENGTH(X) - 1)
|
|
ENDFUNCTION
|