libcaliph/
stats.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2License, v. 2.0. If a copy of the MPL was not distributed with this
3file, You can obtain one at https://mozilla.org/MPL/2.0/.
4Copyright 2021 Peter Dunne */
5
6//! # Stats Module
7//! Provides simple stats formulae
8
9/// Returns the mean of an array of floats
10pub fn mean(values: &[f64]) -> f64 {
11    let length: usize = values.len();
12    if length == 0 {
13        return 0_f64;
14    } else if length == 1 {
15        return values[0];
16    }
17
18    values.iter().sum::<f64>() / length as f64
19}
20
21/// Returns variance of an array of floats
22pub fn variance(values: &[f64]) -> f64 {
23    if values.is_empty() {
24        return 0f64;
25    }
26    let mean = mean(values);
27    values.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / values.len() as f64
28}
29
30/// Returns covariance of two input arrays
31pub fn covariance(x: &[f64], y: &[f64]) -> f64 {
32    if x.len() != y.len() {
33        panic!("x and y must be of equal length.");
34    }
35
36    let length: usize = x.len();
37
38    if length == 0 {
39        return 0_f64;
40    }
41
42    let mean_x = mean(x);
43    let mean_y = mean(y);
44
45    let covariance: f64 = x
46        .iter()
47        .zip(y.iter())
48        .map(|(x, y)| (x - mean_x) * (y - mean_y))
49        .sum();
50
51    covariance / length as f64
52}