Skip to content

Commit f03bf15

Browse files
committed
Add gen_bool method to Rng
1 parent ff72490 commit f03bf15

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/lib.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,21 @@ pub trait Rng: RngCore {
537537
n <= 1 || self.gen_range(0, n) == 0
538538
}
539539

540+
/// Return a bool with a `p` probability of being true.
541+
///
542+
/// # Example
543+
///
544+
/// ```rust
545+
/// use rand::{thread_rng, Rng};
546+
///
547+
/// let mut rng = thread_rng();
548+
/// println!("{}", rng.gen_bool(1.0 / 3.0));
549+
/// ```
550+
fn gen_bool(&mut self, p: f64) -> bool {
551+
assert!(p >= 0.0 && p <= 1.0);
552+
self.sample::<f64, _>(distributions::HighPrecision01) < p
553+
}
554+
540555
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
541556
///
542557
/// # Example

0 commit comments

Comments
 (0)