1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use super::mean::Mean;
pub trait Variance {
type Result;
fn variance(self) -> Self::Result;
}
impl<T> Variance for &[T]
where
T: Copy + Into<f32>,
{
type Result = f32;
fn variance(self) -> f32 {
let mean = self.iter().map(|n| (*n).into()).mean();
let mut sum = 0.0;
for item in self {
let n = (*item).into() - mean;
sum += n * n;
}
sum / (self.len() as f32 - 1.0)
}
}
#[cfg(test)]
mod tests {
use super::Variance;
#[test]
fn variance_test() {
assert_eq!([1.0, 3.0, 5.0].as_ref().variance(), 4.0);
}
}