Variance And Stddev With Iterator Sums

Compute mean with one iterator sum, then variance as the summed squared deviations over the count; this classic sample yields exactly 5, 4, 2.

RustData Integrity

Code

rustsnippet
17 lines
fn main() {
    // 经典样本:均值 5,总体方差 4,标准差 2
    let samples = [2.0_f64, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];

    // 第一遍 iterator sums:sum 除以个数得到均值
    let n = samples.len() as f64;
    let mean = samples.iter().sum::<f64>() / n;

    // 第二遍:每个偏差的平方再求和
    let squared = samples.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>();
    let variance = squared / n;
    let stddev = variance.sqrt();

    println!("mean: {mean:.1}");
    println!("variance: {variance:.1}");
    println!("stddev: {stddev:.1}");
}

What the code does

The part that matters is the function main — everything else is wiring.

Points of care

  • Copy, run: the standard library answers every call in the file.

Applying it

The file’s steps are announced in the output: mean:, variance:, stddev:.

Statements that matter

let squared = samples.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>();
let mean = samples.iter().sum::<f64>() / n;

Interactive Tools for This Topic

FAQ

What does Variance And Stddev With Iterator Sums print when run?
Invoke the file as-is — the `mean:`, `variance:`, `stddev:` prefixes identify which step printed each line.