Commit 06faa7f1 authored by Rui Vieira's avatar Rui Vieira 🍵
Browse files

Add `pdf` and `logpdf` to the Normal distribution

parent ed50586a
* 0.0.2
* Add `pdf` and `logpdf` to the Normal distribution
\ No newline at end of file
......@@ -2,6 +2,7 @@ extern crate rand;
use rand::prelude::*;
use rand::distributions::Normal as N;
use std::f64::consts::PI;
macro_rules! assert_delta {
($x:expr, $y:expr, $d:expr) => {
......@@ -31,21 +32,43 @@ impl Normal {
let v = normal.sample(&mut rand::thread_rng());
return v;
}
pub fn logpdf(&mut self, x: f64) -> f64 {
return -0.5 * (2.0 * PI).ln() - self.std.ln() - (x - self.mean).powi(2) / (2.0 * self.std * self.std)
}
pub fn pdf(&mut self, x: f64) -> f64 {
return self.logpdf(x).exp();
}
}
#[cfg(test)]
mod test_labels {
mod test_normal {
use super::*;
#[test]
fn sample_mean_std() {
let n = (0..1000000);
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);
}
#[test]
fn logpdf() {
let mut normal = Normal::new(0.0, 1.0);
let _logpdf = normal.logpdf(0.0);
print!("{:?}", _logpdf);
assert_delta!(-0.9189385, _logpdf, 1e-5);
}
fn pdf() {
let mut normal = Normal::new(0.0, 1.0);
let _pdf = normal.pdf(0.0);
print!("{:?}", _pdf);
assert_delta!(0.3989423, _pdf, 1e-5);
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment