e_ring/
avg_std.rs

1use crate::Ring;
2use core::ops::{Add, Div, Mul, Sub};
3
4impl<
5        T: Copy
6            + Default
7            + PartialOrd
8            + Sub<Output = T>
9            + Add<Output = T>
10            + Mul<Output = T>
11            + Div<Output = T>
12            + Into<f32>,
13        const N: usize,
14    > Ring<T, N>
15{
16    /// Calculate the average of the elements in the `Ring`
17    pub fn avg(&self) -> f32 {
18        let mut acc = 0.0f32;
19        for el in self.iter() {
20            acc += el.into();
21        }
22        let len: f32 = (self.len() as u16).into(); //FIXME cast
23        acc / len
24    }
25
26    /// Calculate the variance of the elements in the `Ring`, use provided `avg` if `Some`,
27    /// otherwise it calculates it (in the latter case two iterations are required).
28    pub fn var(&self, avg: Option<f32>) -> f32 {
29        let avg = avg.unwrap_or_else(|| self.avg());
30        let mut acc = 0.0f32;
31        for el in self.iter() {
32            let val = el.into() - avg;
33            acc += val * val;
34        }
35        let len: f32 = (self.len() as u16).into(); //FIXME cast
36        acc / len
37    }
38}