Skip to content

gen_ratio -> random_probability, gen_bool -> random_probability_f64 #1527

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update.
- Rename `Rng::gen_iter` to `random_iter` (#1500)
- Rename `rand::thread_rng()` to `rand::rng()`, and remove from the prelude (#1506)
- Remove `rand::random()` from the prelude (#1506)
- Rename `Rng::gen_range` to `random_range`, `gen_bool` to `random_bool`, `gen_ratio` to `random_ratio` (#1505)
- Rename `Rng::gen_range` to `random_range`, `gen_ratio` to `random_probability`, `gen_bool` to `random_probability_f64` (#1505, #1527)

## [0.9.0-alpha.1] - 2024-03-18
- Add the `Slice::num_choices` method to the Slice distribution (#1402)
Expand Down
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
2 changes: 1 addition & 1 deletion src/distr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
//! # Non-uniform sampling
//!
//! Sampling a simple true/false outcome with a given probability has a name:
//! the [`Bernoulli`] distribution (this is used by [`Rng::random_bool`]).
//! the [`Bernoulli`] distribution (this is used by [`Rng::random_probability_f64`]).
//!
//! For weighted sampling from a sequence of discrete values, use the
//! [`WeightedIndex`] distribution.
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_f64](Rng::random_probability_f64)(<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