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
use rand::distributions::Distribution;
use rand::{self, Rng};
use std::f64::consts::{PI, SQRT_2};
pub trait Pdf<T> {
fn pdf(&self, x: &T) -> f64;
}
pub trait Cdf<T> {
fn cdf(&self, x: &T) -> f64;
}
#[derive(Debug, Default, Clone, Copy)]
pub struct StandardNormal;
impl Distribution<f64> for StandardNormal {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
rand_distr::StandardNormal.sample(rng)
}
}
impl Pdf<f64> for StandardNormal {
fn pdf(&self, x: &f64) -> f64 {
let a = (2.0 * PI).sqrt();
let b = -x.powi(2) / 2.0;
b.exp() / a
}
}
impl Pdf<(f64, f64)> for StandardNormal {
fn pdf(&self, x: &(f64, f64)) -> f64 {
let a = 1.0 / (2.0 * PI);
let b = x.0 * x.0 + x.1 * x.1;
a * (-0.5 * b).exp()
}
}
impl Cdf<f64> for StandardNormal {
fn cdf(&self, &x: &f64) -> f64 {
0.5 * libm::erfc(-x / SQRT_2)
}
}