1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use crate::{Distribution, Random, Rng};
#[derive(Copy, Clone, Debug)]
pub struct Bernoulli {
p: f64,
}
impl Bernoulli {
#[inline]
pub const fn new(p: f64) -> Bernoulli {
Bernoulli { p }
}
}
impl Distribution<bool> for Bernoulli {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut Random<R>) -> bool {
<crate::distributions::Float01 as Distribution<f64>>::sample(&crate::distributions::Float01, rng) <= self.p
}
}
#[test]
fn test_trivial() {
let mut rng = crate::new();
let always_false = Bernoulli::new(0.0);
let always_true = Bernoulli::new(1.0);
for _ in 0..5 {
assert_eq!(rng.sample::<bool, _>(&always_false), false);
assert_eq!(rng.sample::<bool, _>(&always_true), true);
assert_eq!(Distribution::<bool>::sample(&always_false, &mut rng), false);
assert_eq!(Distribution::<bool>::sample(&always_true, &mut rng), true);
}
}