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
41
42
43
44
45
46
47
48
49
50
51
extern crate rand;

use rand::prelude::*;
use rand::distributions::Normal as N;

macro_rules! assert_delta {
    ($x:expr, $y:expr, $d:expr) => {
        if !(($x - $y).abs() < $d || ($y - $x).abs() < $d) { panic!(); }
    }
}

fn mean(numbers: &Vec<f64>) -> f64 {
    numbers.iter().sum::<f64>() as f64 / numbers.len() as f64
}

pub struct Normal {
    mean : f64,
    std : f64
}

impl Normal {
    pub fn new(mean: f64, std: f64) -> Normal {
        return Normal {
            mean : mean,
            std: std,
        }
    }

    pub fn sample(&mut self) -> f64 {
        let normal = N::new(self.mean, self.std);
        let v = normal.sample(&mut rand::thread_rng());
        return v;
    }
}

#[cfg(test)]
mod test_labels {

    use super::*;

    #[test]
    fn sample_mean_std() {
        let n = (0..1000000);
        let mut normal = Normal::new(0.0, 1.0);
        let samples = n.map(|i| normal.sample()).collect::<Vec<f64>>();
        let mu = mean(&samples);
        print!("{:?}", mu);
        assert_delta!(0.0, mu, 1e-3);
    }

}