rand_simple/distributions/half_normal.rs
1use crate::create_state;
2use crate::standard_distributions::standard_normal;
3
4/// Half Normal Distribution
5/// # Example
6/// ```
7/// let mut half_normal = rand_simple::HalfNormal::new([1192_u32, 765_u32]);
8/// assert_eq!(format!("{half_normal}"), "HN(Std^2) = HN(1^2)");
9/// println!("Returns a random number -> {}", half_normal.sample());
10///
11/// // If you want to change the parameters of the random variable
12/// let variance: f64 = 2_f64;
13/// let result: Result<f64, &str> = half_normal.try_set_params(variance);
14/// assert_eq!(format!("{half_normal}"), "HN(Std^2) = HN(2^2)");
15/// println!("Returns a random number -> {}", half_normal.sample());
16/// ```
17pub struct HalfNormal {
18 xyzuv0: [u32; 5], // 状態変数
19 xyzuv1: [u32; 5], // 状態変数
20 std: f64, // 標準偏差
21}
22
23impl HalfNormal {
24 /// Constructor
25 /// * `seeds` - Seeds for random number generation. Adjusted on the constructor side to ensure they are not the same.
26 pub fn new(seeds: [u32; 2]) -> Self {
27 let adjusted_seeds = crate::adjust_seeds!(seeds);
28 Self {
29 xyzuv0: create_state(adjusted_seeds[0]),
30 xyzuv1: create_state(adjusted_seeds[1]),
31 std: 1_f64,
32 }
33 }
34
35 /// Generate a random number.
36 pub fn sample(&mut self) -> f64 {
37 standard_normal(&mut self.xyzuv0, &mut self.xyzuv1).abs() * self.std
38 }
39
40 /// Modify the parameters of the random variable.
41 /// * `std` - Standard deviation
42 pub fn try_set_params(&mut self, std: f64) -> Result<f64, &'static str> {
43 if std <= 0_f64 {
44 Err("Standard deviation is less than or equal to 0. The random variable's parameters will remain unchanged.")
45 } else {
46 self.std = std;
47 Ok(std)
48 }
49 }
50}
51
52impl core::fmt::Display for HalfNormal {
53 /// Formatter for displaying in functions like println! macro
54 /// * Standard deviation
55 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
56 write!(f, "HN(Std^2) = HN({}^2)", self.std)?;
57 Ok(())
58 }
59}