Skip to content

Commit 6df9d1f

Browse files
committed
Add accuracy note to gen_bool
1 parent bf9c5b2 commit 6df9d1f

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

src/lib.rs

+10
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,16 @@ pub trait Rng: RngCore {
508508
/// let mut rng = thread_rng();
509509
/// println!("{}", rng.gen_bool(1.0 / 3.0));
510510
/// ```
511+
///
512+
/// # Accuracy note
513+
///
514+
/// `gen_bool` uses 32 bits of the RNG, so if you use it to generate close
515+
/// to or more than 2^32 results, a tiny bias may become noticable.
516+
/// A notable consequence of the method used here is that the worst case is
517+
/// `rng.gen_bool(0.0)`: it has a chance of 1 in 2^32 of being true, while
518+
/// it should always be false. But using `gen_bool` to consume *many* values
519+
/// from an RNG just to consistently generate `false` does not match with
520+
/// the intent of this method.
511521
fn gen_bool(&mut self, p: f64) -> bool {
512522
assert!(p >= 0.0 && p <= 1.0);
513523
// If `p` is constant, this will be evaluated at compile-time.

0 commit comments

Comments
 (0)