1 // Copyright 2018 Developers of the Rand project.
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
9 //! The Bernoulli distribution.
12 use distributions
::Distribution
;
14 /// The Bernoulli distribution.
16 /// This is a special case of the Binomial distribution where `n = 1`.
21 /// use rand::distributions::{Bernoulli, Distribution};
23 /// let d = Bernoulli::new(0.3);
24 /// let v = d.sample(&mut rand::thread_rng());
25 /// println!("{} is from a Bernoulli distribution", v);
30 /// This `Bernoulli` distribution uses 64 bits from the RNG (a `u64`),
31 /// so only probabilities that are multiples of 2<sup>-64</sup> can be
33 #[derive(Clone, Copy, Debug)]
34 pub struct Bernoulli
{
35 /// Probability of success, relative to the maximal integer.
39 // To sample from the Bernoulli distribution we use a method that compares a
40 // random `u64` value `v < (p * 2^64)`.
42 // If `p == 1.0`, the integer `v` to compare against can not represented as a
43 // `u64`. We manually set it to `u64::MAX` instead (2^64 - 1 instead of 2^64).
44 // Note that value of `p < 1.0` can never result in `u64::MAX`, because an
45 // `f64` only has 53 bits of precision, and the next largest value of `p` will
46 // result in `2^64 - 2048`.
48 // Also there is a 100% theoretical concern: if someone consistenly wants to
49 // generate `true` using the Bernoulli distribution (i.e. by using a probability
50 // of `1.0`), just using `u64::MAX` is not enough. On average it would return
51 // false once every 2^64 iterations. Some people apparently care about this
54 // That is why we special-case `u64::MAX` to always return `true`, without using
55 // the RNG, and pay the performance price for all uses that *are* reasonable.
56 // Luckily, if `new()` and `sample` are close, the compiler can optimize out the
58 const ALWAYS_TRUE
: u64 = ::core
::u64::MAX
;
60 // This is just `2.0.powi(64)`, but written this way because it is not available
62 const SCALE
: f64 = 2.0 * (1u64 << 63) as f64;
65 /// Construct a new `Bernoulli` with the given probability of success `p`.
69 /// If `p < 0` or `p > 1`.
73 /// For `p = 1.0`, the resulting distribution will always generate true.
74 /// For `p = 0.0`, the resulting distribution will always generate false.
76 /// This method is accurate for any input `p` in the range `[0, 1]` which is
77 /// a multiple of 2<sup>-64</sup>. (Note that not all multiples of
78 /// 2<sup>-64</sup> in `[0, 1]` can be represented as a `f64`.)
80 pub fn new(p
: f64) -> Bernoulli
{
81 if p
< 0.0 || p
>= 1.0 {
82 if p
== 1.0 { return Bernoulli { p_int: ALWAYS_TRUE }
}
83 panic
!("Bernoulli::new not called with 0.0 <= p <= 1.0");
85 Bernoulli { p_int: (p * SCALE) as u64 }
88 /// Construct a new `Bernoulli` with the probability of success of
89 /// `numerator`-in-`denominator`. I.e. `new_ratio(2, 3)` will return
90 /// a `Bernoulli` with a 2-in-3 chance, or about 67%, of returning `true`.
92 /// If `numerator == denominator` then the returned `Bernoulli` will always
93 /// return `true`. If `numerator == 0` it will always return `false`.
97 /// If `denominator == 0` or `numerator > denominator`.
100 pub fn from_ratio(numerator
: u32, denominator
: u32) -> Bernoulli
{
101 assert
!(numerator
<= denominator
);
102 if numerator
== denominator
{
103 return Bernoulli { p_int: ::core::u64::MAX }
105 let p_int
= ((numerator
as f64 / denominator
as f64) * SCALE
) as u64;
110 impl Distribution
<bool
> for Bernoulli
{
112 fn sample
<R
: Rng
+ ?Sized
>(&self, rng
: &mut R
) -> bool
{
113 // Make sure to always return true for p = 1.0.
114 if self.p_int
== ALWAYS_TRUE { return true; }
115 let v
: u64 = rng
.gen();
123 use distributions
::Distribution
;
124 use super::Bernoulli
;
128 let mut r
= ::test
::rng(1);
129 let always_false
= Bernoulli
::new(0.0);
130 let always_true
= Bernoulli
::new(1.0);
132 assert_eq
!(r
.sample
::<bool
, _
>(&always_false
), false);
133 assert_eq
!(r
.sample
::<bool
, _
>(&always_true
), true);
134 assert_eq
!(Distribution
::<bool
>::sample(&always_false
, &mut r
), false);
135 assert_eq
!(Distribution
::<bool
>::sample(&always_true
, &mut r
), true);
143 const DENOM
: u32 = 10;
144 let d1
= Bernoulli
::new(P
);
145 let d2
= Bernoulli
::from_ratio(NUM
, DENOM
);
146 const N
: u32 = 100_000;
148 let mut sum1
: u32 = 0;
149 let mut sum2
: u32 = 0;
150 let mut rng
= ::test
::rng(2);
152 if d1
.sample(&mut rng
) {
155 if d2
.sample(&mut rng
) {
159 let avg1
= (sum1
as f64) / (N
as f64);
160 assert
!((avg1
- P
).abs() < 5e
-3);
162 let avg2
= (sum2
as f64) / (N
as f64);
163 assert
!((avg2
- (NUM
as f64)/(DENOM
as f64)).abs() < 5e
-3);