Skip to main content

variance

Function variance 

Source
pub fn variance(data: &[f64]) -> Option<f64>
Expand description

Computes the sample variance using Welford’s online algorithm.

Returns the sample (unbiased) variance with Bessel’s correction (denominator n − 1).

§Algorithm

Welford’s method maintains a running mean and sum of squared deviations, avoiding catastrophic cancellation inherent in the naive formula Var = E[X²] − (E[X])².

Reference: Welford (1962), Technometrics 4(3), pp. 419–420.

§Complexity

Time: O(n), Space: O(1)

§Returns

  • None if data.len() < 2 or contains NaN/Inf.

§Examples

use u_numflow::stats::variance;
let v = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
assert!((variance(&v).unwrap() - 4.571428571428571).abs() < 1e-10);