numeric_statistics/f64/
standard_deviation.rs

1use super::variance;
2
3/// Calculate statistical standard deviation for values.
4///
5/// Return NaN if the values are empty.
6///
7pub fn standard_deviation<T: AsRef<[f64]>>(values: T) -> f64 {
8    standard_deviation_with_variance(variance(&values))
9}
10
11/// Calculate statistical standard deviation for values, 
12/// given a pre-calculated variance value.
13///
14/// Return NaN if the values are empty.
15///
16pub fn standard_deviation_with_variance(variance: f64) -> f64 {
17    variance.sqrt()
18}
19
20#[cfg(test)]
21mod test {
22    use super::*;
23
24    #[test]
25    fn test_empty() {
26        let x: &[f64] = &[];
27        assert!(standard_deviation(x).is_nan());
28    }
29
30    #[test]
31    fn test_nan() {
32        let x: &[f64] = &[f64::NAN];
33        assert!(standard_deviation(x).is_nan());
34    }
35
36    #[test]
37    fn test_value() {
38        let x: &[f64] = &[1.0];
39        assert_eq_float!(standard_deviation(x), 0.0);
40    }
41
42    #[test]
43    fn test_values_ascending() {
44        let x = &[1.0, 2.0, 4.0];
45        assert_eq_float!(standard_deviation(x), 1.5275252316519465);
46    }
47
48    #[test]
49    fn test_values_ascending_and_nans() {
50        let x = &[1.0, f64::NAN, 2.0, f64::NAN, 4.0];
51        assert_eq_float!(standard_deviation(x), 1.5275252316519465);
52    }
53
54}