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.
Code
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
Statistics CalculatorCompute count, sum, mean, median, minimum, maximum, range, variance, and standard deviation for a number list.A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text StatisticsCount characters, words, lines, sentences, paragraphs, and estimated reading time entirely in the browser with no text sent to a server.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.