public static double variance ( FlatDataCollection flatDataCollection , boolean isSample ) { /* Uses the formal Variance = E(X^2) - mean^2 */ int n = 0 ; double mean = 0.0 ; double squaredMean = 0.0 ; Iterator < Double > it = flatDataCollection . iteratorDouble ( ) ; while ( it . hasNext ( ) ) { Double v = it . next ( ) ; if ( v != null ) { ++ n ; mean += v ; squaredMean += v * v ; } } if ( n <= 1 ) { throw new IllegalArgumentException ( "The provided collection must have more than 1 elements." ) ; } mean /= n ; squaredMean /= n ; double variance = squaredMean - mean * mean ; /* Unbiased for sample */ if ( isSample ) { variance *= n / ( n - 1.0 ) ; } return variance ; }
Calculates the Variance