plottery_lib/maths/
random.rs

1use rand::Rng;
2use rand_distr::{Distribution, Normal, SkewNormal};
3
4use super::thread_local::RNG;
5
6/// uniform random float between `from` and `to`
7pub fn rand_range(from: f32, to: f32) -> f32 {
8    RNG.with_borrow_mut(|rng: &mut rand::prelude::StdRng| rng.gen_range(from..to))
9}
10
11/// uniform random integer between `from` and `to`
12pub fn rand_range_i(from: i32, to: i32) -> i32 {
13    RNG.with_borrow_mut(|rng: &mut rand::prelude::StdRng| rng.gen_range(from..to))
14}
15
16/// random boolean with given `chance` of being true
17pub fn coin(chance: f32) -> bool {
18    RNG.with_borrow_mut(|rng| rng.gen::<f32>() < chance)
19}
20
21/// see [`rand_distr::Normal`]
22pub fn rand_normal(mean: f32, std_dev: f32) -> f32 {
23    let normal = Normal::new(mean, std_dev).unwrap_or_else(|_| {
24        panic!(
25            "Invalid parameters for normal distribution: mean: {}, std_dev: {}",
26            mean, std_dev
27        )
28    });
29    RNG.with_borrow_mut(|rng| normal.sample(rng))
30}
31
32/// see [`rand_distr::SkewNormal`]
33pub fn rand_normal_skewed(location: f32, scale: f32, shape: f32) -> f32 {
34    let normal_skewed = SkewNormal::new(location, scale, shape).unwrap_or_else(|_| {
35        panic!(
36            "Invalid parameters for skewed normal distribution: location: {}, scale: {}, shape: {}",
37            location, scale, shape
38        )
39    });
40    RNG.with_borrow_mut(|rng| normal_skewed.sample(rng))
41}
42
43/// see [`rand_distr::Exp`]
44pub fn rand_exponential(lambda: f32) -> f32 {
45    let exponential = rand_distr::Exp::new(lambda).unwrap_or_else(|_| {
46        panic!(
47            "Invalid parameter for exponential distribution: lambda: {}",
48            lambda
49        )
50    });
51    RNG.with_borrow_mut(|rng| exponential.sample(rng))
52}