lib_jsl_random/distributions/
gaussian.rs1use std::{f64::consts::PI, ops::Mul};
2
3use crate::uniform_generator::UniformGenerator;
4
5pub fn gaussian_distribution_box_muller<U>(
9 uniform_generator: &mut U,
10 mean: f64,
11 sd: f64,
12) -> (f64, f64)
13where
14 U: UniformGenerator,
15{
16 let uniform_sample_0: f64 = uniform_generator.next_f64();
17 let uniform_sample_1: f64 = uniform_generator.next_f64();
18 let a = (1.0 - uniform_sample_0).ln().mul(-2.0).sqrt();
20 let z1 = a * uniform_sample_1.mul(2.0 * PI).cos();
21 let z2 = a * uniform_sample_1.mul(2.0 * PI).sin();
22 (z1 * sd + mean, z2 * sd + mean)
23}
24pub fn gaussian_distribution_box_muller_vec<U>(
28 count : usize,
29 uniform_generator: &mut U,
30 mean: f64,
31 sd: f64,
32)-> Vec<f64>
33where
34 U: UniformGenerator{
35 let mut result = Vec::<f64>::with_capacity(count+1);
36 if count == 1{
37 let z = gaussian_distribution_box_muller(uniform_generator, mean, sd);
38 result.push(z.0);
39 }else{
40 while result.len() < count{
41 let z = gaussian_distribution_box_muller(uniform_generator, mean, sd);
42 result.push(z.0);
43 result.push(z.1);
44 }
45 result.truncate(count);
47 }
48 result
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54 use crate::distributions::chi_square::chi_square_distribution;
55 use crate::uniform_generator::UniformRNG;
56
57 #[test]
58 fn the_vector_has_the_requested_length() {
59 let mut rng = UniformRNG::from_seed(3);
61 for count in 0..8 {
62 assert_eq!(gaussian_distribution_box_muller_vec(count, &mut rng, 0.0, 1.0).len(), count);
63 }
64 }
65
66 #[test]
67 fn chi_square_with_even_degrees_has_mean_k() {
68 let mut rng = UniformRNG::from_seed(5);
70 for k in [2usize, 4] {
71 let n = 40_000;
72 let mean = (0..n).map(|_| chi_square_distribution(&mut rng, k, 0.0, 1.0)).sum::<f64>() / n as f64;
73 assert!((mean - k as f64).abs() < 0.1, "k = {k}: mean {mean}");
74 }
75 }
76}