1// Copyright 2018 Developers of the Rand project.
2//
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.
89//! The Bernoulli distribution `Bernoulli(p)`.
1011use crate::distr::Distribution;
12use crate::{Rng, RngExt};
13use core::fmt;
1415#[cfg(feature = "serde")]
16use serde::{Deserialize, Serialize};
1718/// The [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution) `Bernoulli(p)`.
19///
20/// This distribution describes a single boolean random variable, which is true
21/// with probability `p` and false with probability `1 - p`.
22/// It is a special case of the Binomial distribution with `n = 1`.
23///
24/// # Plot
25///
26/// The following plot shows the Bernoulli distribution with `p = 0.1`,
27/// `p = 0.5`, and `p = 0.9`.
28///
29/// 
30///
31/// # Example
32///
33/// ```rust
34/// use rand::distr::{Bernoulli, Distribution};
35///
36/// let d = Bernoulli::new(0.3).unwrap();
37/// let v = d.sample(&mut rand::rng());
38/// println!("{} is from a Bernoulli distribution", v);
39/// ```
40///
41/// # Precision
42///
43/// This `Bernoulli` distribution uses 64 bits from the RNG (a `u64`),
44/// so only probabilities that are multiples of 2<sup>-64</sup> can be
45/// represented.
46#[derive(#[automatically_derived]
impl ::core::clone::Clone for Bernoulli {
#[inline]
fn clone(&self) -> Bernoulli {
let _: ::core::clone::AssertParamIsClone<u64>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for Bernoulli { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for Bernoulli {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "Bernoulli",
"p_int", &&self.p_int)
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for Bernoulli {
#[inline]
fn eq(&self, other: &Bernoulli) -> bool { self.p_int == other.p_int }
}PartialEq)]
47#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
48pub struct Bernoulli {
49/// Probability of success, relative to the maximal integer.
50p_int: u64,
51}
5253// To sample from the Bernoulli distribution we use a method that compares a
54// random `u64` value `v < (p * 2^64)`.
55//
56// If `p == 1.0`, the integer `v` to compare against can not represented as a
57// `u64`. We manually set it to `u64::MAX` instead (2^64 - 1 instead of 2^64).
58// Note that value of `p < 1.0` can never result in `u64::MAX`, because an
59// `f64` only has 53 bits of precision, and the next largest value of `p` will
60// result in `2^64 - 2048`.
61//
62// Also there is a 100% theoretical concern: if someone consistently wants to
63// generate `true` using the Bernoulli distribution (i.e. by using a probability
64// of `1.0`), just using `u64::MAX` is not enough. On average it would return
65// false once every 2^64 iterations. Some people apparently care about this
66// case.
67//
68// That is why we special-case `u64::MAX` to always return `true`, without using
69// the RNG, and pay the performance price for all uses that *are* reasonable.
70// Luckily, if `new()` and `sample` are close, the compiler can optimize out the
71// extra check.
72const ALWAYS_TRUE: u64 = u64::MAX;
7374// This is just `2.0.powi(64)`, but written this way because it is not available
75// in `no_std` mode.
76const SCALE: f64 = 2.0 * (1u64 << 63) as f64;
7778/// Error type returned from [`Bernoulli::new`].
79#[derive(#[automatically_derived]
impl ::core::clone::Clone for BernoulliError {
#[inline]
fn clone(&self) -> BernoulliError { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BernoulliError { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for BernoulliError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f, "InvalidProbability")
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for BernoulliError {
#[inline]
fn eq(&self, other: &BernoulliError) -> bool { true }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for BernoulliError {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_receiver_is_total_eq(&self) {}
}Eq)]
80pub enum BernoulliError {
81/// `p < 0` or `p > 1`.
82InvalidProbability,
83}
8485impl fmt::Displayfor BernoulliError {
86fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87f.write_str(match self {
88 BernoulliError::InvalidProbability => "p is outside [0, 1] in Bernoulli distribution",
89 })
90 }
91}
9293impl core::error::Errorfor BernoulliError {}
9495impl Bernoulli {
96/// Construct a new `Bernoulli` with the given probability of success `p`.
97 ///
98 /// # Precision
99 ///
100 /// For `p = 1.0`, the resulting distribution will always generate true.
101 /// For `p = 0.0`, the resulting distribution will always generate false.
102 ///
103 /// This method is accurate for any input `p` in the range `[0, 1]` which is
104 /// a multiple of 2<sup>-64</sup>. (Note that not all multiples of
105 /// 2<sup>-64</sup> in `[0, 1]` can be represented as a `f64`.)
106#[inline]
107pub fn new(p: f64) -> Result<Bernoulli, BernoulliError> {
108if !(0.0..1.0).contains(&p) {
109if p == 1.0 {
110return Ok(Bernoulli { p_int: ALWAYS_TRUE });
111 }
112return Err(BernoulliError::InvalidProbability);
113 }
114Ok(Bernoulli {
115 p_int: (p * SCALE) as u64,
116 })
117 }
118119/// Construct a new `Bernoulli` with the probability of success of
120 /// `numerator`-in-`denominator`. I.e. `new_ratio(2, 3)` will return
121 /// a `Bernoulli` with a 2-in-3 chance, or about 67%, of returning `true`.
122 ///
123 /// return `true`. If `numerator == 0` it will always return `false`.
124 /// For `numerator > denominator` and `denominator == 0`, this returns an
125 /// error. Otherwise, for `numerator == denominator`, samples are always
126 /// true; for `numerator == 0` samples are always false.
127#[inline]
128pub fn from_ratio(numerator: u32, denominator: u32) -> Result<Bernoulli, BernoulliError> {
129if numerator > denominator || denominator == 0 {
130return Err(BernoulliError::InvalidProbability);
131 }
132if numerator == denominator {
133return Ok(Bernoulli { p_int: ALWAYS_TRUE });
134 }
135let p_int = ((f64::from(numerator) / f64::from(denominator)) * SCALE) as u64;
136Ok(Bernoulli { p_int })
137 }
138139#[inline]
140/// Returns the probability (`p`) of the distribution.
141 ///
142 /// This value may differ slightly from the input due to loss of precision.
143pub fn p(&self) -> f64 {
144if self.p_int == ALWAYS_TRUE {
1451.0
146} else {
147 (self.p_int as f64) / SCALE148 }
149 }
150}
151152impl Distribution<bool> for Bernoulli {
153#[inline]
154fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> bool {
155// Make sure to always return true for p = 1.0.
156if self.p_int == ALWAYS_TRUE {
157return true;
158 }
159let v: u64 = rng.random();
160v < self.p_int
161 }
162}
163164#[cfg(test)]
165mod test {
166use super::Bernoulli;
167use crate::RngExt;
168use crate::distr::Distribution;
169170#[test]
171 #[cfg(feature = "serde")]
172fn test_serializing_deserializing_bernoulli() {
173let coin_flip = Bernoulli::new(0.5).unwrap();
174let de_coin_flip: Bernoulli =
175 postcard::from_bytes(&postcard::to_allocvec(&coin_flip).unwrap()).unwrap();
176177assert_eq!(coin_flip.p_int, de_coin_flip.p_int);
178 }
179180#[test]
181fn test_trivial() {
182// We prefer to be explicit here.
183#![allow(clippy::bool_assert_comparison)]
184185let mut r = crate::test::rng(1);
186let always_false = Bernoulli::new(0.0).unwrap();
187let always_true = Bernoulli::new(1.0).unwrap();
188for _ in 0..5 {
189assert_eq!(r.sample::<bool, _>(&always_false), false);
190assert_eq!(r.sample::<bool, _>(&always_true), true);
191assert_eq!(Distribution::<bool>::sample(&always_false, &mut r), false);
192assert_eq!(Distribution::<bool>::sample(&always_true, &mut r), true);
193 }
194 }
195196#[test]
197 #[cfg_attr(miri, ignore)] // Miri is too slow
198fn test_average() {
199const P: f64 = 0.3;
200const NUM: u32 = 3;
201const DENOM: u32 = 10;
202let d1 = Bernoulli::new(P).unwrap();
203let d2 = Bernoulli::from_ratio(NUM, DENOM).unwrap();
204const N: u32 = 100_000;
205206let mut sum1: u32 = 0;
207let mut sum2: u32 = 0;
208let mut rng = crate::test::rng(2);
209for _ in 0..N {
210if d1.sample(&mut rng) {
211 sum1 += 1;
212 }
213if d2.sample(&mut rng) {
214 sum2 += 1;
215 }
216 }
217let avg1 = (sum1 as f64) / (N as f64);
218assert!((avg1 - P).abs() < 5e-3);
219220let avg2 = (sum2 as f64) / (N as f64);
221assert!((avg2 - (NUM as f64) / (DENOM as f64)).abs() < 5e-3);
222 }
223224#[test]
225fn value_stability() {
226let mut rng = crate::test::rng(3);
227let distr = Bernoulli::new(0.4532).unwrap();
228let mut buf = [false; 10];
229for x in &mut buf {
230*x = rng.sample(distr);
231 }
232assert_eq!(
233 buf,
234 [
235true, false, false, true, false, false, true, true, true, true
236]
237 );
238 }
239240#[test]
241fn bernoulli_distributions_can_be_compared() {
242assert_eq!(Bernoulli::new(1.0), Bernoulli::new(1.0));
243 }
244}