Skip to content

Commit

Permalink
gen_ratio -> random_probability, gen_bool -> random_probability_f64
Browse files Browse the repository at this point in the history
  • Loading branch information
oconnor663 committed Nov 13, 2024
1 parent 585b29f commit f0e4bf3
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 37 deletions.
10 changes: 5 additions & 5 deletions benches/benches/bool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ criterion_group!(
criterion_main!(benches);

pub fn bench(c: &mut Criterion) {
let mut g = c.benchmark_group("random_bool");
let mut g = c.benchmark_group("random_probability_f64");
g.sample_size(1000);
g.warm_up_time(core::time::Duration::from_millis(500));
g.measurement_time(core::time::Duration::from_millis(1000));
Expand All @@ -33,25 +33,25 @@ pub fn bench(c: &mut Criterion) {

g.bench_function("const", |b| {
let mut rng = Pcg32::from_rng(&mut rand::rng());
b.iter(|| rng.random_bool(0.18))
b.iter(|| rng.random_probability_f64(0.18))
});

g.bench_function("var", |b| {
let mut rng = Pcg32::from_rng(&mut rand::rng());
let p = rng.random();
b.iter(|| rng.random_bool(p))
b.iter(|| rng.random_probability_f64(p))
});

g.bench_function("ratio_const", |b| {
let mut rng = Pcg32::from_rng(&mut rand::rng());
b.iter(|| rng.random_ratio(2, 3))
b.iter(|| rng.random_probability(2, 3))
});

g.bench_function("ratio_var", |b| {
let mut rng = Pcg32::from_rng(&mut rand::rng());
let d = rng.random_range(1..=100);
let n = rng.random_range(0..=d);
b.iter(|| rng.random_ratio(n, d));
b.iter(|| rng.random_probability(n, d));
});

g.bench_function("bernoulli_const", |b| {
Expand Down
18 changes: 9 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,12 +217,12 @@ where
/// Return a bool with a probability `p` of being true.
///
/// This function is shorthand for
/// <code>[rng()].[random_bool](Rng::random_bool)(<var>p</var>)</code>.
/// <code>[rng()].[random_probability_f32](Rng::random_probability_f32)(<var>p</var>)</code>.
///
/// # Example
///
/// ```
/// println!("{}", rand::random_bool(1.0 / 3.0));
/// println!("{}", rand::random_probability_f64(1.0 / 3.0));
/// ```
///
/// # Panics
Expand All @@ -231,14 +231,14 @@ where
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
#[inline]
#[track_caller]
pub fn random_bool(p: f64) -> bool {
rng().random_bool(p)
pub fn random_probability_f64(p: f64) -> bool {
rng().random_probability_f64(p)
}

/// Return a bool with a probability of `numerator/denominator` of being
/// true.
///
/// That is, `random_ratio(2, 3)` has chance of 2 in 3, or about 67%, of
/// That is, `random_probability(2, 3)` has chance of 2 in 3, or about 67%, of
/// returning true. If `numerator == denominator`, then the returned value
/// is guaranteed to be `true`. If `numerator == 0`, then the returned
/// value is guaranteed to be `false`.
Expand All @@ -247,7 +247,7 @@ pub fn random_bool(p: f64) -> bool {
/// sampling from the same `numerator` and `denominator` repeatedly.
///
/// This function is shorthand for
/// <code>[rng()].[random_ratio](Rng::random_ratio)(<var>numerator</var>, <var>denominator</var>)</code>.
/// <code>[rng()].[random_probability](Rng::random_probability)(<var>numerator</var>, <var>denominator</var>)</code>.
///
/// # Panics
///
Expand All @@ -256,15 +256,15 @@ pub fn random_bool(p: f64) -> bool {
/// # Example
///
/// ```
/// println!("{}", rand::random_ratio(2, 3));
/// println!("{}", rand::random_probability(2, 3));
/// ```
///
/// [`Bernoulli`]: distr::Bernoulli
#[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))]
#[inline]
#[track_caller]
pub fn random_ratio(numerator: u32, denominator: u32) -> bool {
rng().random_ratio(numerator, denominator)
pub fn random_probability(numerator: u32, denominator: u32) -> bool {
rng().random_probability(numerator, denominator)
}

/// Fill any type implementing [`Fill`] with random data
Expand Down
30 changes: 15 additions & 15 deletions src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ pub trait Rng: RngCore {
/// use rand::Rng;
///
/// let mut rng = rand::rng();
/// println!("{}", rng.random_bool(1.0 / 3.0));
/// println!("{}", rng.random_probability_f64(1.0 / 3.0));
/// ```
///
/// # Panics
Expand All @@ -188,7 +188,7 @@ pub trait Rng: RngCore {
/// [`Bernoulli`]: distr::Bernoulli
#[inline]
#[track_caller]
fn random_bool(&mut self, p: f64) -> bool {
fn random_probability_f64(&mut self, p: f64) -> bool {
match distr::Bernoulli::new(p) {
Ok(d) => self.sample(d),
Err(_) => panic!("p={:?} is outside range [0.0, 1.0]", p),
Expand All @@ -198,7 +198,7 @@ pub trait Rng: RngCore {
/// Return a bool with a probability of `numerator/denominator` of being
/// true.
///
/// That is, `random_ratio(2, 3)` has chance of 2 in 3, or about 67%, of
/// That is, `random_probability(2, 3)` has chance of 2 in 3, or about 67%, of
/// returning true. If `numerator == denominator`, then the returned value
/// is guaranteed to be `true`. If `numerator == 0`, then the returned
/// value is guaranteed to be `false`.
Expand All @@ -216,13 +216,13 @@ pub trait Rng: RngCore {
/// use rand::Rng;
///
/// let mut rng = rand::rng();
/// println!("{}", rng.random_ratio(2, 3));
/// println!("{}", rng.random_probability(2, 3));
/// ```
///
/// [`Bernoulli`]: distr::Bernoulli
#[inline]
#[track_caller]
fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool {
fn random_probability(&mut self, numerator: u32, denominator: u32) -> bool {
match distr::Bernoulli::from_ratio(numerator, denominator) {
Ok(d) => self.sample(d),
Err(_) => panic!(
Expand Down Expand Up @@ -339,18 +339,18 @@ pub trait Rng: RngCore {
self.random_range(range)
}

/// Alias for [`Rng::random_bool`].
/// Alias for [`Rng::random_probability_f64`].
#[inline]
#[deprecated(since = "0.9.0", note = "Renamed to `random_bool`")]
#[deprecated(since = "0.9.0", note = "Renamed to `random_probability_f64`")]
fn gen_bool(&mut self, p: f64) -> bool {
self.random_bool(p)
self.random_probability_f64(p)
}

/// Alias for [`Rng::random_ratio`].
/// Alias for [`Rng::random_probability`].
#[inline]
#[deprecated(since = "0.9.0", note = "Renamed to `random_ratio`")]
#[deprecated(since = "0.9.0", note = "Renamed to `random_probability`")]
fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool {
self.random_ratio(numerator, denominator)
self.random_probability(numerator, denominator)
}
}

Expand Down Expand Up @@ -560,11 +560,11 @@ mod test {

#[test]
#[allow(clippy::bool_assert_comparison)]
fn test_random_bool() {
fn test_random_probability_f64() {
let mut r = rng(105);
for _ in 0..5 {
assert_eq!(r.random_bool(0.0), false);
assert_eq!(r.random_bool(1.0), true);
assert_eq!(r.random_probability_f64(0.0), false);
assert_eq!(r.random_probability_f64(1.0), true);
}
}

Expand Down Expand Up @@ -611,7 +611,7 @@ mod test {
let mut sum: u32 = 0;
let mut rng = rng(111);
for _ in 0..N {
if rng.random_ratio(NUM, DENOM) {
if rng.random_probability(NUM, DENOM) {
sum += 1;
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/seq/coin_flipper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,17 @@ impl<R: RngCore> CoinFlipper<R> {
/// Returns true with a probability of 1 / d
/// Uses an expected two bits of randomness
/// Panics if d == 0
pub fn random_ratio_one_over(&mut self, d: usize) -> bool {
pub fn random_probability_one_over(&mut self, d: usize) -> bool {
debug_assert_ne!(d, 0);
// This uses the same logic as `random_ratio` but is optimized for the case that
// This uses the same logic as `random_probability` but is optimized for the case that
// the starting numerator is one (which it always is for `Sequence::Choose()`)

// In this case (but not `random_ratio`), this way of calculating c is always accurate
// In this case (but not `random_probability`), this way of calculating c is always accurate
let c = (usize::BITS - 1 - d.leading_zeros()).min(32);

if self.flip_c_heads(c) {
let numerator = 1 << c;
self.random_ratio(numerator, d)
self.random_probability(numerator, d)
} else {
false
}
Expand All @@ -46,7 +46,7 @@ impl<R: RngCore> CoinFlipper<R> {
#[inline]
/// Returns true with a probability of n / d
/// Uses an expected two bits of randomness
fn random_ratio(&mut self, mut n: usize, d: usize) -> bool {
fn random_probability(&mut self, mut n: usize, d: usize) -> bool {
// Explanation:
// We are trying to return true with a probability of n / d
// If n >= d, we can just return true
Expand Down
6 changes: 3 additions & 3 deletions src/seq/iterator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub trait IteratorRandom: Iterator + Sized {
return result;
}
consumed += 1;
if coin_flipper.random_ratio_one_over(consumed) {
if coin_flipper.random_probability_one_over(consumed) {
result = elem;
}
}
Expand Down Expand Up @@ -152,7 +152,7 @@ pub trait IteratorRandom: Iterator + Sized {
let (lower, _) = self.size_hint();
if lower >= 2 {
let highest_selected = (0..lower)
.filter(|ix| coin_flipper.random_ratio_one_over(consumed + ix + 1))
.filter(|ix| coin_flipper.random_probability_one_over(consumed + ix + 1))
.last();

consumed += lower;
Expand All @@ -170,7 +170,7 @@ pub trait IteratorRandom: Iterator + Sized {
return result;
}

if coin_flipper.random_ratio_one_over(consumed + 1) {
if coin_flipper.random_probability_one_over(consumed + 1) {
result = elem;
}
consumed += 1;
Expand Down

0 comments on commit f0e4bf3

Please sign in to comment.