Skip to main content

lib_jsl_random/distributions/
gaussian.rs

1use std::{f64::consts::PI, ops::Mul};
2
3use crate::uniform_generator::UniformGenerator;
4
5// ANCHOR: box_muller
6/// Gaussian distribution (via Box - Muller transform)
7/// Yields two independent samples
8pub 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    // 1 − u lies in (0, 1], so the logarithm is finite (u itself can be exactly 0).
19    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}
24// ANCHOR_END: box_muller
25
26// Utility for efficiently creating a vector of gaussian random variables
27pub 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        // Each draw makes two values: drop the spare one for an odd count.
46        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        // Even counts once returned two extra values (and a count of 0 returned two).
60        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        // Through the bug above, chi-square with even k summed k + 2 squares: mean k + 2.
69        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}