rand_simple/distributions/uniform.rs
1use crate::standard_distributions::{generate_random_state, xorshift160_0_to_1};
2
3/// Uniform distribution
4/// # Example
5/// ```
6/// let mut uniform = rand_simple::Uniform::new(1192_u32);
7/// assert_eq!(format!("{uniform}"), "Range (Closed Interval): [0, 1]");
8/// println!("Returns a random number -> {}", uniform.sample());
9///
10/// // When changing the parameters of the random variable
11/// let min: f64 = -1_f64;
12/// let max: f64 = 1_f64;
13/// let result: Result<(f64, f64), &str> = uniform.try_set_params(min, max);
14/// assert_eq!(format!("{uniform}"), "Range (Closed Interval): [-1, 1]");
15/// println!("Returns a random number -> {}", uniform.sample());
16/// ```
17pub struct Uniform {
18 xyzuv: [u32; 5], // 状態変数
19 min: f64, // 最小値
20 max: f64, // 最大値
21}
22
23impl Uniform {
24 /// Constructor
25 /// * `_seed` - The seed for the random number generator
26 pub fn new(_seed: u32) -> Self {
27 Self {
28 xyzuv: generate_random_state(_seed),
29 min: 0_f64,
30 max: 1_f64,
31 }
32 }
33
34 /// Calculate a random number.
35 /// # Returns
36 /// A random floating-point number within the specified range.
37 pub fn sample(&mut self) -> f64 {
38 xorshift160_0_to_1(&mut self.xyzuv) * (self.max - self.min) + self.min
39 }
40
41 /// Attempt to modify the parameters of the random variable.
42 /// * `min` - Minimum value
43 /// * `max` - Maximum value
44 pub fn try_set_params(&mut self, min: f64, max: f64) -> Result<(f64, f64), &'static str> {
45 if min >= max {
46 Err("The minimum and maximum values are equal or the minimum value is greater. The parameters of the random variable will remain unchanged.")
47 } else {
48 self.min = min;
49 self.max = max;
50 Ok((self.min, self.max))
51 }
52 }
53}
54
55impl core::fmt::Display for Uniform {
56 /// Formatter for displaying with println! macro and others.
57 /// * Range (Closed Interval)
58 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
59 write!(f, "Range (Closed Interval): [{}, {}]", self.min, self.max)?;
60 Ok(())
61 }
62}