Skip to content

Instantly share code, notes, and snippets.

@leiless
Created August 31, 2023 12:33
Show Gist options
  • Save leiless/12f6764354a0702f8791818c9ef8a743 to your computer and use it in GitHub Desktop.
Save leiless/12f6764354a0702f8791818c9ef8a743 to your computer and use it in GitHub Desktop.
Standard deviation in Rust
fn mean(data: &[u32]) -> f64 {
let sum = data.iter().sum::<u32>() as f64;
let count = data.len();
sum / count as f64
}
fn std_deviation(data: &[u32]) -> f64 {
if data.len() != 0 {
let data_mean = mean(data);
let variance = data.iter().map(|v| {
let diff = (*v as f64) - data_mean;
diff * diff
}).sum::<f64>() / data.len() as f64;
variance.sqrt()
} else {
0.0
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
//let data = [3, 1, 6, 1, 5, 8, 1, 8, 10, 11];
let data = [1, 1, 1, 1, 1, 2];
let data_std_deviation = std_deviation(&data);
println!("Standard deviation is {}", data_std_deviation);
Ok(())
}
@leiless
Copy link
Author

leiless commented Aug 31, 2023

$ ./rust-test
Standard deviation is 0.3726779962499649

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment