Created
August 31, 2023 12:33
-
-
Save leiless/12f6764354a0702f8791818c9ef8a743 to your computer and use it in GitHub Desktop.
Standard deviation in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(()) | |
} |
Author
leiless
commented
Aug 31, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment