Skip to content

Commit 6a9e0d7

Browse files
committed
Add gen_bool method to Rng
1 parent a76487c commit 6a9e0d7

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/lib.rs

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

540+
/// Return a bool with a probability `p` 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+
// If `p` is constant, this will be evaluated at compile-time.
553+
let p_int = (p * core::u32::MAX as f64) as u32;
554+
p_int > self.gen()
555+
}
556+
540557
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
541558
///
542559
/// # Example
@@ -1082,6 +1099,15 @@ mod test {
10821099
assert_eq!(r.gen_weighted_bool(1), true);
10831100
}
10841101

1102+
#[test]
1103+
fn test_gen_bool() {
1104+
let mut r = rng(105);
1105+
for _ in 0..5 {
1106+
assert_eq!(r.gen_bool(0.0), false);
1107+
assert_eq!(r.gen_bool(1.0), true);
1108+
}
1109+
}
1110+
10851111
#[test]
10861112
fn test_choose() {
10871113
let mut r = rng(107);

0 commit comments

Comments
 (0)