File tree 1 file changed +26
-0
lines changed
1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change @@ -537,6 +537,23 @@ pub trait Rng: RngCore {
537
537
n <= 1 || self . gen_range ( 0 , n) == 0
538
538
}
539
539
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
+
540
557
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
541
558
///
542
559
/// # Example
@@ -1082,6 +1099,15 @@ mod test {
1082
1099
assert_eq ! ( r. gen_weighted_bool( 1 ) , true ) ;
1083
1100
}
1084
1101
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
+
1085
1111
#[ test]
1086
1112
fn test_choose ( ) {
1087
1113
let mut r = rng ( 107 ) ;
You can’t perform that action at this time.
0 commit comments