From dbae5c82e5315cc0e7371622a169e6984a8b3fce Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 12 Nov 2024 17:01:16 +0000 Subject: [PATCH 1/7] Rename Standard -> StandardUniform --- README.md | 2 +- benches/benches/array.rs | 6 +-- benches/benches/bool.rs | 2 +- benches/benches/generators.rs | 2 +- benches/benches/standard.rs | 6 +-- rand_distr/src/cauchy.rs | 12 ++--- rand_distr/src/inverse_gaussian.rs | 8 ++-- rand_distr/src/lib.rs | 4 +- rand_distr/src/normal_inverse_gaussian.rs | 8 ++-- rand_distr/src/poisson.rs | 14 +++--- rand_distr/src/triangular.rs | 10 ++--- rand_distr/src/zeta.rs | 10 ++--- rand_distr/src/zipf.rs | 12 ++--- src/distr/distribution.rs | 8 ++-- src/distr/float.rs | 28 +++++++----- src/distr/integer.rs | 46 +++++++++---------- src/distr/mod.rs | 42 +++++++++--------- src/distr/other.rs | 54 +++++++++++------------ src/distr/uniform.rs | 2 +- src/distr/uniform_float.rs | 2 +- src/distr/uniform_int.rs | 6 +-- src/lib.rs | 12 ++--- src/rng.rs | 34 +++++++------- src/rngs/mock.rs | 4 +- 24 files changed, 169 insertions(+), 165 deletions(-) diff --git a/README.md b/README.md index 58f363896b..b8e089099f 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Rand is a set of crates supporting (pseudo-)random generators: With broad support for random value generation and random processes: -- [`Standard`](https://docs.rs/rand/latest/rand/distributions/struct.Standard.html) random value sampling, +- [`StandardUniform`](https://docs.rs/rand/latest/rand/distributions/struct.StandardUniform.html) random value sampling, [`Uniform`](https://docs.rs/rand/latest/rand/distributions/struct.Uniform.html)-ranged value sampling and [more](https://docs.rs/rand/latest/rand/distr/index.html) - Samplers for a large number of non-uniform random number distributions via our own diff --git a/benches/benches/array.rs b/benches/benches/array.rs index a21e902cb9..063516337b 100644 --- a/benches/benches/array.rs +++ b/benches/benches/array.rs @@ -9,7 +9,7 @@ //! Generating/filling arrays and iterators of output use criterion::{criterion_group, criterion_main, Criterion}; -use rand::distr::Standard; +use rand::distr::StandardUniform; use rand::prelude::*; use rand_pcg::Pcg64Mcg; @@ -36,7 +36,7 @@ pub fn bench(c: &mut Criterion) { g.bench_function("u16_sample_iter", |b| { let mut rng = Pcg64Mcg::from_rng(&mut rand::rng()); b.iter(|| { - let v: Vec = Standard.sample_iter(&mut rng).take(512).collect(); + let v: Vec = StandardUniform.sample_iter(&mut rng).take(512).collect(); v }); }); @@ -70,7 +70,7 @@ pub fn bench(c: &mut Criterion) { g.bench_function("u64_sample_iter", |b| { let mut rng = Pcg64Mcg::from_rng(&mut rand::rng()); b.iter(|| { - let v: Vec = Standard.sample_iter(&mut rng).take(128).collect(); + let v: Vec = StandardUniform.sample_iter(&mut rng).take(128).collect(); v }); }); diff --git a/benches/benches/bool.rs b/benches/benches/bool.rs index 989a938d9f..8ff8c67602 100644 --- a/benches/benches/bool.rs +++ b/benches/benches/bool.rs @@ -28,7 +28,7 @@ pub fn bench(c: &mut Criterion) { g.bench_function("standard", |b| { let mut rng = Pcg32::from_rng(&mut rand::rng()); - b.iter(|| rng.sample::(rand::distr::Standard)) + b.iter(|| rng.sample::(rand::distr::StandardUniform)) }); g.bench_function("const", |b| { diff --git a/benches/benches/generators.rs b/benches/benches/generators.rs index cdfab9b2f7..95361cd203 100644 --- a/benches/benches/generators.rs +++ b/benches/benches/generators.rs @@ -171,7 +171,7 @@ pub fn init_from_seed(c: &mut Criterion) { fn bench(g: &mut BenchmarkGroup, name: &str) where - rand::distr::Standard: Distribution<::Seed>, + rand::distr::StandardUniform: Distribution<::Seed>, { g.bench_function(name, |b| { let mut rng = Pcg32::from_os_rng(); diff --git a/benches/benches/standard.rs b/benches/benches/standard.rs index cd88ea66a2..ffe7ea5de1 100644 --- a/benches/benches/standard.rs +++ b/benches/benches/standard.rs @@ -9,7 +9,7 @@ use core::time::Duration; use criterion::measurement::WallTime; use criterion::{criterion_group, criterion_main, BenchmarkGroup, Criterion}; -use rand::distr::{Alphanumeric, Standard}; +use rand::distr::{Alphanumeric, StandardUniform}; use rand::prelude::*; use rand_distr::{Open01, OpenClosed01}; use rand_pcg::Pcg64Mcg; @@ -34,14 +34,14 @@ where } pub fn bench(c: &mut Criterion) { - let mut g = c.benchmark_group("Standard"); + let mut g = c.benchmark_group("StandardUniform"); g.sample_size(1000); g.warm_up_time(Duration::from_millis(500)); g.measurement_time(Duration::from_millis(1000)); macro_rules! do_ty { ($t:ty) => { - bench_ty::<$t, Standard>(&mut g, stringify!($t)); + bench_ty::<$t, StandardUniform>(&mut g, stringify!($t)); }; ($t:ty, $($tt:ty),*) => { do_ty!($t); diff --git a/rand_distr/src/cauchy.rs b/rand_distr/src/cauchy.rs index 4042b4fbf7..8f0faad386 100644 --- a/rand_distr/src/cauchy.rs +++ b/rand_distr/src/cauchy.rs @@ -9,7 +9,7 @@ //! The Cauchy distribution `Cauchy(x₀, γ)`. -use crate::{Distribution, Standard}; +use crate::{Distribution, StandardUniform}; use core::fmt; use num_traits::{Float, FloatConst}; use rand::Rng; @@ -58,7 +58,7 @@ use rand::Rng; pub struct Cauchy where F: Float + FloatConst, - Standard: Distribution, + StandardUniform: Distribution, { median: F, scale: F, @@ -85,7 +85,7 @@ impl std::error::Error for Error {} impl Cauchy where F: Float + FloatConst, - Standard: Distribution, + StandardUniform: Distribution, { /// Construct a new `Cauchy` with the given shape parameters /// `median` the peak location and `scale` the scale factor. @@ -100,11 +100,11 @@ where impl Distribution for Cauchy where F: Float + FloatConst, - Standard: Distribution, + StandardUniform: Distribution, { fn sample(&self, rng: &mut R) -> F { // sample from [0, 1) - let x = Standard.sample(rng); + let x = StandardUniform.sample(rng); // get standard cauchy random number // note that π/2 is not exactly representable, even if x=0.5 the result is finite let comp_dev = (F::PI() * x).tan(); @@ -166,7 +166,7 @@ mod test { fn value_stability() { fn gen_samples(m: F, s: F, buf: &mut [F]) where - Standard: Distribution, + StandardUniform: Distribution, { let distr = Cauchy::new(m, s).unwrap(); let mut rng = crate::test::rng(353); diff --git a/rand_distr/src/inverse_gaussian.rs b/rand_distr/src/inverse_gaussian.rs index 8614a15e66..354c2e0598 100644 --- a/rand_distr/src/inverse_gaussian.rs +++ b/rand_distr/src/inverse_gaussian.rs @@ -1,6 +1,6 @@ //! The inverse Gaussian distribution `IG(μ, λ)`. -use crate::{Distribution, Standard, StandardNormal}; +use crate::{Distribution, StandardNormal, StandardUniform}; use core::fmt; use num_traits::Float; use rand::Rng; @@ -53,7 +53,7 @@ pub struct InverseGaussian where F: Float, StandardNormal: Distribution, - Standard: Distribution, + StandardUniform: Distribution, { mean: F, shape: F, @@ -63,7 +63,7 @@ impl InverseGaussian where F: Float, StandardNormal: Distribution, - Standard: Distribution, + StandardUniform: Distribution, { /// Construct a new `InverseGaussian` distribution with the given mean and /// shape. @@ -85,7 +85,7 @@ impl Distribution for InverseGaussian where F: Float, StandardNormal: Distribution, - Standard: Distribution, + StandardUniform: Distribution, { #[allow(clippy::many_single_char_names)] fn sample(&self, rng: &mut R) -> F diff --git a/rand_distr/src/lib.rs b/rand_distr/src/lib.rs index 03fad85c91..efd316b09c 100644 --- a/rand_distr/src/lib.rs +++ b/rand_distr/src/lib.rs @@ -34,7 +34,7 @@ //! The following are re-exported: //! //! - The [`Distribution`] trait and [`DistIter`] helper type -//! - The [`Standard`], [`Alphanumeric`], [`Uniform`], [`OpenClosed01`], +//! - The [`StandardUniform`], [`Alphanumeric`], [`Uniform`], [`OpenClosed01`], //! [`Open01`], [`Bernoulli`], and [`WeightedIndex`] distributions //! //! ## Distributions @@ -95,7 +95,7 @@ use rand::Rng; pub use rand::distr::{ uniform, Alphanumeric, Bernoulli, BernoulliError, DistIter, Distribution, Open01, OpenClosed01, - Standard, Uniform, + StandardUniform, Uniform, }; pub use self::beta::{Beta, Error as BetaError}; diff --git a/rand_distr/src/normal_inverse_gaussian.rs b/rand_distr/src/normal_inverse_gaussian.rs index cd9c1781ce..6ad2e58fe6 100644 --- a/rand_distr/src/normal_inverse_gaussian.rs +++ b/rand_distr/src/normal_inverse_gaussian.rs @@ -1,4 +1,4 @@ -use crate::{Distribution, InverseGaussian, Standard, StandardNormal}; +use crate::{Distribution, InverseGaussian, StandardNormal, StandardUniform}; use core::fmt; use num_traits::Float; use rand::Rng; @@ -54,7 +54,7 @@ pub struct NormalInverseGaussian where F: Float, StandardNormal: Distribution, - Standard: Distribution, + StandardUniform: Distribution, { beta: F, inverse_gaussian: InverseGaussian, @@ -64,7 +64,7 @@ impl NormalInverseGaussian where F: Float, StandardNormal: Distribution, - Standard: Distribution, + StandardUniform: Distribution, { /// Construct a new `NormalInverseGaussian` distribution with the given alpha (tail heaviness) and /// beta (asymmetry) parameters. @@ -94,7 +94,7 @@ impl Distribution for NormalInverseGaussian where F: Float, StandardNormal: Distribution, - Standard: Distribution, + StandardUniform: Distribution, { fn sample(&self, rng: &mut R) -> F where diff --git a/rand_distr/src/poisson.rs b/rand_distr/src/poisson.rs index 20b41ace64..3e4421259b 100644 --- a/rand_distr/src/poisson.rs +++ b/rand_distr/src/poisson.rs @@ -9,7 +9,7 @@ //! The Poisson distribution `Poisson(λ)`. -use crate::{Cauchy, Distribution, Standard}; +use crate::{Cauchy, Distribution, StandardUniform}; use core::fmt; use num_traits::{Float, FloatConst}; use rand::Rng; @@ -55,7 +55,7 @@ use rand::Rng; pub struct Poisson(Method) where F: Float + FloatConst, - Standard: Distribution; + StandardUniform: Distribution; /// Error type returned from [`Poisson::new`]. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -130,7 +130,7 @@ enum Method { impl Poisson where F: Float + FloatConst, - Standard: Distribution, + StandardUniform: Distribution, { /// Construct a new `Poisson` with the given shape parameter /// `lambda`. @@ -172,7 +172,7 @@ where impl Distribution for KnuthMethod where F: Float + FloatConst, - Standard: Distribution, + StandardUniform: Distribution, { fn sample(&self, rng: &mut R) -> F { let mut result = F::one(); @@ -188,7 +188,7 @@ where impl Distribution for RejectionMethod where F: Float + FloatConst, - Standard: Distribution, + StandardUniform: Distribution, { fn sample(&self, rng: &mut R) -> F { // The algorithm from Numerical Recipes in C @@ -238,7 +238,7 @@ where impl Distribution for Poisson where F: Float + FloatConst, - Standard: Distribution, + StandardUniform: Distribution, { #[inline] fn sample(&self, rng: &mut R) -> F { @@ -255,7 +255,7 @@ mod test { fn test_poisson_avg_gen(lambda: F, tol: F) where - Standard: Distribution, + StandardUniform: Distribution, { let poisson = Poisson::new(lambda).unwrap(); let mut rng = crate::test::rng(123); diff --git a/rand_distr/src/triangular.rs b/rand_distr/src/triangular.rs index 9342ba024a..05a46e57ec 100644 --- a/rand_distr/src/triangular.rs +++ b/rand_distr/src/triangular.rs @@ -7,7 +7,7 @@ // except according to those terms. //! The triangular distribution. -use crate::{Distribution, Standard}; +use crate::{Distribution, StandardUniform}; use core::fmt; use num_traits::Float; use rand::Rng; @@ -43,7 +43,7 @@ use rand::Rng; pub struct Triangular where F: Float, - Standard: Distribution, + StandardUniform: Distribution, { min: F, max: F, @@ -76,7 +76,7 @@ impl std::error::Error for TriangularError {} impl Triangular where F: Float, - Standard: Distribution, + StandardUniform: Distribution, { /// Set up the Triangular distribution with defined `min`, `max` and `mode`. #[inline] @@ -94,11 +94,11 @@ where impl Distribution for Triangular where F: Float, - Standard: Distribution, + StandardUniform: Distribution, { #[inline] fn sample(&self, rng: &mut R) -> F { - let f: F = rng.sample(Standard); + let f: F = rng.sample(StandardUniform); let diff_mode_min = self.mode - self.min; let range = self.max - self.min; let f_range = f * range; diff --git a/rand_distr/src/zeta.rs b/rand_distr/src/zeta.rs index e06208c94e..f93f167d7c 100644 --- a/rand_distr/src/zeta.rs +++ b/rand_distr/src/zeta.rs @@ -8,7 +8,7 @@ //! The Zeta distribution. -use crate::{Distribution, Standard}; +use crate::{Distribution, StandardUniform}; use core::fmt; use num_traits::Float; use rand::{distr::OpenClosed01, Rng}; @@ -68,7 +68,7 @@ use rand::{distr::OpenClosed01, Rng}; pub struct Zeta where F: Float, - Standard: Distribution, + StandardUniform: Distribution, OpenClosed01: Distribution, { s_minus_1: F, @@ -96,7 +96,7 @@ impl std::error::Error for Error {} impl Zeta where F: Float, - Standard: Distribution, + StandardUniform: Distribution, OpenClosed01: Distribution, { /// Construct a new `Zeta` distribution with given `s` parameter. @@ -117,7 +117,7 @@ where impl Distribution for Zeta where F: Float, - Standard: Distribution, + StandardUniform: Distribution, OpenClosed01: Distribution, { #[inline] @@ -135,7 +135,7 @@ where let t = (F::one() + F::one() / x).powf(self.s_minus_1); - let v = rng.sample(Standard); + let v = rng.sample(StandardUniform); if v * x * (t - F::one()) * self.b <= t * (self.b - F::one()) { return x; } diff --git a/rand_distr/src/zipf.rs b/rand_distr/src/zipf.rs index 45a8bf2b5c..f2e80d3790 100644 --- a/rand_distr/src/zipf.rs +++ b/rand_distr/src/zipf.rs @@ -8,7 +8,7 @@ //! The Zipf distribution. -use crate::{Distribution, Standard}; +use crate::{Distribution, StandardUniform}; use core::fmt; use num_traits::Float; use rand::Rng; @@ -56,7 +56,7 @@ use rand::Rng; pub struct Zipf where F: Float, - Standard: Distribution, + StandardUniform: Distribution, { s: F, t: F, @@ -87,7 +87,7 @@ impl std::error::Error for Error {} impl Zipf where F: Float, - Standard: Distribution, + StandardUniform: Distribution, { /// Construct a new `Zipf` distribution for a set with `n` elements and a /// frequency rank exponent `s`. @@ -137,20 +137,20 @@ where impl Distribution for Zipf where F: Float, - Standard: Distribution, + StandardUniform: Distribution, { #[inline] fn sample(&self, rng: &mut R) -> F { let one = F::one(); loop { - let inv_b = self.inv_cdf(rng.sample(Standard)); + let inv_b = self.inv_cdf(rng.sample(StandardUniform)); let x = (inv_b + one).floor(); let mut ratio = x.powf(-self.s); if x > one { ratio = ratio * inv_b.powf(self.s) }; - let y = rng.sample(Standard); + let y = rng.sample(StandardUniform); if y < ratio { return x; } diff --git a/src/distr/distribution.rs b/src/distr/distribution.rs index cab4ce626f..f9385ec617 100644 --- a/src/distr/distribution.rs +++ b/src/distr/distribution.rs @@ -48,12 +48,12 @@ pub trait Distribution { /// # Example /// /// ``` - /// use rand::distr::{Distribution, Alphanumeric, Uniform, Standard}; + /// use rand::distr::{Distribution, Alphanumeric, Uniform, StandardUniform}; /// /// let mut rng = rand::rng(); /// /// // Vec of 16 x f32: - /// let v: Vec = Standard.sample_iter(&mut rng).take(16).collect(); + /// let v: Vec = StandardUniform.sample_iter(&mut rng).take(16).collect(); /// /// // String: /// let s: String = Alphanumeric @@ -246,7 +246,7 @@ mod tests { #[test] #[cfg(feature = "alloc")] fn test_dist_string() { - use crate::distr::{Alphanumeric, DistString, Standard}; + use crate::distr::{Alphanumeric, DistString, StandardUniform}; use core::str; let mut rng = crate::test::rng(213); @@ -254,7 +254,7 @@ mod tests { assert_eq!(s1.len(), 20); assert_eq!(str::from_utf8(s1.as_bytes()), Ok(s1.as_str())); - let s2 = Standard.sample_string(&mut rng, 20); + let s2 = StandardUniform.sample_string(&mut rng, 20); assert_eq!(s2.chars().count(), 20); assert_eq!(str::from_utf8(s2.as_bytes()), Ok(s2.as_str())); } diff --git a/src/distr/float.rs b/src/distr/float.rs index 11d02f76f0..ec380b4bd4 100644 --- a/src/distr/float.rs +++ b/src/distr/float.rs @@ -9,7 +9,7 @@ //! Basic floating-point number distributions use crate::distr::utils::{FloatAsSIMD, FloatSIMDUtils, IntAsSIMD}; -use crate::distr::{Distribution, Standard}; +use crate::distr::{Distribution, StandardUniform}; use crate::Rng; use core::mem; #[cfg(feature = "simd_support")] @@ -26,7 +26,7 @@ use serde::{Deserialize, Serialize}; /// 53 most significant bits of a `u64` are used. The conversion uses the /// multiplicative method. /// -/// See also: [`Standard`] which samples from `[0, 1)`, [`Open01`] +/// See also: [`StandardUniform`] which samples from `[0, 1)`, [`Open01`] /// which samples from `(0, 1)` and [`Uniform`] which samples from arbitrary /// ranges. /// @@ -39,7 +39,7 @@ use serde::{Deserialize, Serialize}; /// println!("f32 from (0, 1): {}", val); /// ``` /// -/// [`Standard`]: crate::distr::Standard +/// [`StandardUniform`]: crate::distr::StandardUniform /// [`Open01`]: crate::distr::Open01 /// [`Uniform`]: crate::distr::uniform::Uniform #[derive(Clone, Copy, Debug, Default)] @@ -53,7 +53,7 @@ pub struct OpenClosed01; /// the 23 most significant random bits of an `u32` are used, for `f64` 52 from /// an `u64`. The conversion uses a transmute-based method. /// -/// See also: [`Standard`] which samples from `[0, 1)`, [`OpenClosed01`] +/// See also: [`StandardUniform`] which samples from `[0, 1)`, [`OpenClosed01`] /// which samples from `(0, 1]` and [`Uniform`] which samples from arbitrary /// ranges. /// @@ -66,7 +66,7 @@ pub struct OpenClosed01; /// println!("f32 from (0, 1): {}", val); /// ``` /// -/// [`Standard`]: crate::distr::Standard +/// [`StandardUniform`]: crate::distr::StandardUniform /// [`OpenClosed01`]: crate::distr::OpenClosed01 /// [`Uniform`]: crate::distr::uniform::Uniform #[derive(Clone, Copy, Debug, Default)] @@ -105,7 +105,7 @@ macro_rules! float_impls { } $(#[cfg($meta)])? - impl Distribution<$ty> for Standard { + impl Distribution<$ty> for StandardUniform { fn sample(&self, rng: &mut R) -> $ty { // Multiply-based method; 24/53 random bits; [0, 1) interval. // We use the most significant bits because for simple RNGs @@ -186,7 +186,7 @@ mod tests { fn $fnn() { let two = $ty::splat(2.0); - // Standard + // StandardUniform let mut zeros = StepRng::new(0, 0); assert_eq!(zeros.random::<$ty>(), $ZERO); let mut one = StepRng::new(1 << 8 | 1 << (8 + 32), 0); @@ -234,7 +234,7 @@ mod tests { fn $fnn() { let two = $ty::splat(2.0); - // Standard + // StandardUniform let mut zeros = StepRng::new(0, 0); assert_eq!(zeros.random::<$ty>(), $ZERO); let mut one = StepRng::new(1 << 11, 0); @@ -289,9 +289,13 @@ mod tests { assert_eq!(&buf, expected); } - test_samples(&Standard, 0f32, &[0.0035963655, 0.7346052, 0.09778172]); test_samples( - &Standard, + &StandardUniform, + 0f32, + &[0.0035963655, 0.7346052, 0.09778172], + ); + test_samples( + &StandardUniform, 0f64, &[0.7346051961657583, 0.20298547462974248, 0.8166436635290655], ); @@ -317,7 +321,7 @@ mod tests { // SIMD types. test_samples( - &Standard, + &StandardUniform, f32x2::from([0.0, 0.0]), &[ f32x2::from([0.0035963655, 0.7346052]), @@ -327,7 +331,7 @@ mod tests { ); test_samples( - &Standard, + &StandardUniform, f64x2::from([0.0, 0.0]), &[ f64x2::from([0.7346051961657583, 0.20298547462974248]), diff --git a/src/distr/integer.rs b/src/distr/integer.rs index 8cf9ffc688..f20f34e0eb 100644 --- a/src/distr/integer.rs +++ b/src/distr/integer.rs @@ -6,9 +6,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! The implementations of the `Standard` distribution for integer types. +//! The implementations of the `StandardUniform` distribution for integer types. -use crate::distr::{Distribution, Standard}; +use crate::distr::{Distribution, StandardUniform}; use crate::Rng; #[cfg(all(target_arch = "x86", feature = "simd_support"))] use core::arch::x86::__m512i; @@ -25,35 +25,35 @@ use core::num::{ #[cfg(feature = "simd_support")] use core::simd::*; -impl Distribution for Standard { +impl Distribution for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> u8 { rng.next_u32() as u8 } } -impl Distribution for Standard { +impl Distribution for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> u16 { rng.next_u32() as u16 } } -impl Distribution for Standard { +impl Distribution for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> u32 { rng.next_u32() } } -impl Distribution for Standard { +impl Distribution for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> u64 { rng.next_u64() } } -impl Distribution for Standard { +impl Distribution for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> u128 { // Use LE; we explicitly generate one value before the next. @@ -65,7 +65,7 @@ impl Distribution for Standard { macro_rules! impl_int_from_uint { ($ty:ty, $uty:ty) => { - impl Distribution<$ty> for Standard { + impl Distribution<$ty> for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> $ty { rng.random::<$uty>() as $ty @@ -82,7 +82,7 @@ impl_int_from_uint! { i128, u128 } macro_rules! impl_nzint { ($ty:ty, $new:path) => { - impl Distribution<$ty> for Standard { + impl Distribution<$ty> for StandardUniform { fn sample(&self, rng: &mut R) -> $ty { loop { if let Some(nz) = $new(rng.random()) { @@ -110,7 +110,7 @@ impl_nzint!(NonZeroI128, NonZeroI128::new); macro_rules! x86_intrinsic_impl { ($meta:meta, $($intrinsic:ident),+) => {$( #[cfg($meta)] - impl Distribution<$intrinsic> for Standard { + impl Distribution<$intrinsic> for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> $intrinsic { // On proper hardware, this should compile to SIMD instructions @@ -131,7 +131,7 @@ macro_rules! simd_impl { /// /// [`simd_support`]: https://github.com/rust-random/rand#crate-features #[cfg(feature = "simd_support")] - impl Distribution> for Standard + impl Distribution> for StandardUniform where LaneCount: SupportedLaneCount, { @@ -174,29 +174,29 @@ mod tests { fn test_integers() { let mut rng = crate::test::rng(806); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); - rng.sample::(Standard); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); } #[test] fn value_stability() { fn test_samples(zero: T, expected: &[T]) where - Standard: Distribution, + StandardUniform: Distribution, { let mut rng = crate::test::rng(807); let mut buf = [zero; 3]; for x in &mut buf { - *x = rng.sample(Standard); + *x = rng.sample(StandardUniform); } assert_eq!(&buf, expected); } diff --git a/src/distr/mod.rs b/src/distr/mod.rs index a1b2802c94..1565305f79 100644 --- a/src/distr/mod.rs +++ b/src/distr/mod.rs @@ -28,31 +28,31 @@ //! [`Uniform`] allows specification of its sample space as a range within `T`). //! //! -//! # The `Standard` distribution +//! # The `StandardUniform` distribution //! -//! The [`Standard`] distribution is important to mention. This is the +//! The [`StandardUniform`] distribution is important to mention. This is the //! distribution used by [`Rng::random`] and represents the "default" way to //! produce a random value for many different types, including most primitive //! types, tuples, arrays, and a few derived types. See the documentation of -//! [`Standard`] for more details. +//! [`StandardUniform`] for more details. //! -//! Implementing `Distribution` for [`Standard`] for user types `T` makes it +//! Implementing `Distribution` for [`StandardUniform`] for user types `T` makes it //! possible to generate type `T` with [`Rng::random`], and by extension also //! with the [`random`] function. //! //! ## Random characters //! //! [`Alphanumeric`] is a simple distribution to sample random letters and -//! numbers of the `char` type; in contrast [`Standard`] may sample any valid +//! numbers of the `char` type; in contrast [`StandardUniform`] may sample any valid //! `char`. //! //! //! # Uniform numeric ranges //! -//! The [`Uniform`] distribution is more flexible than [`Standard`], but also +//! The [`Uniform`] distribution is more flexible than [`StandardUniform`], but also //! more specialised: it supports fewer target types, but allows the sample //! space to be specified as an arbitrary range within its target type `T`. -//! Both [`Standard`] and [`Uniform`] are in some sense uniform distributions. +//! Both [`StandardUniform`] and [`Uniform`] are in some sense uniform distributions. //! //! Values may be sampled from this distribution using [`Rng::sample(Range)`] or //! by creating a distribution object with [`Uniform::new`], @@ -61,7 +61,7 @@ //! `Uniform` object than to call [`Rng::sample(Range)`]. //! //! User types `T` may also implement `Distribution` for [`Uniform`], -//! although this is less straightforward than for [`Standard`] (see the +//! although this is less straightforward than for [`StandardUniform`] (see the //! documentation in the [`uniform`] module). Doing so enables generation of //! values of type `T` with [`Rng::sample(Range)`]. //! @@ -69,9 +69,9 @@ //! //! There are surprisingly many ways to uniformly generate random floats. A //! range between 0 and 1 is standard, but the exact bounds (open vs closed) -//! and accuracy differ. In addition to the [`Standard`] distribution Rand offers +//! and accuracy differ. In addition to the [`StandardUniform`] distribution Rand offers //! [`Open01`] and [`OpenClosed01`]. See "Floating point implementation" section of -//! [`Standard`] documentation for more details. +//! [`StandardUniform`] documentation for more details. //! //! # Non-uniform sampling //! @@ -148,37 +148,37 @@ use crate::Rng; /// variants but cannot produce zero. /// * SIMD types like x86's [`__m128i`], `std::simd`'s [`u32x4`]/[`f32x4`]/ /// [`mask32x4`] (requires [`simd_support`]), where each lane is distributed -/// like their scalar `Standard` variants. See the list of `Standard` +/// like their scalar `StandardUniform` variants. See the list of `StandardUniform` /// implementations for more. /// -/// The `Standard` distribution also supports generation of the following +/// The `StandardUniform` distribution also supports generation of the following /// compound types where all component types are supported: /// /// * Tuples (up to 12 elements): each element is generated sequentially. /// * Arrays: each element is generated sequentially; /// see also [`Rng::fill`] which supports arbitrary array length for integer /// and float types and tends to be faster for `u32` and smaller types. -/// Note that [`Rng::fill`] and `Standard`'s array support are *not* equivalent: +/// Note that [`Rng::fill`] and `StandardUniform`'s array support are *not* equivalent: /// the former is optimised for integer types (using fewer RNG calls for /// element types smaller than the RNG word size), while the latter supports -/// any element type supported by `Standard`. +/// any element type supported by `StandardUniform`. /// * `Option` first generates a `bool`, and if true generates and returns /// `Some(value)` where `value: T`, otherwise returning `None`. /// /// ## Custom implementations /// -/// The [`Standard`] distribution may be implemented for user types as follows: +/// The [`StandardUniform`] distribution may be implemented for user types as follows: /// /// ``` /// # #![allow(dead_code)] /// use rand::Rng; -/// use rand::distr::{Distribution, Standard}; +/// use rand::distr::{Distribution, StandardUniform}; /// /// struct MyF32 { /// x: f32, /// } /// -/// impl Distribution for Standard { +/// impl Distribution for StandardUniform { /// fn sample(&self, rng: &mut R) -> MyF32 { /// MyF32 { x: rng.random() } /// } @@ -188,14 +188,14 @@ use crate::Rng; /// ## Example usage /// ``` /// use rand::prelude::*; -/// use rand::distr::Standard; +/// use rand::distr::StandardUniform; /// -/// let val: f32 = StdRng::from_os_rng().sample(Standard); +/// let val: f32 = StdRng::from_os_rng().sample(StandardUniform); /// println!("f32 from [0, 1): {}", val); /// ``` /// /// # Floating point implementation -/// The floating point implementations for `Standard` generate a random value in +/// The floating point implementations for `StandardUniform` generate a random value in /// the half-open interval `[0, 1)`, i.e. including 0 but not 1. /// /// All values that can be generated are of the form `n * ε/2`. For `f32` @@ -219,4 +219,4 @@ use crate::Rng; /// [`simd_support`]: https://github.com/rust-random/rand#crate-features #[derive(Clone, Copy, Debug, Default)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct Standard; +pub struct StandardUniform; diff --git a/src/distr/other.rs b/src/distr/other.rs index f350731477..6b6c6c24f3 100644 --- a/src/distr/other.rs +++ b/src/distr/other.rs @@ -6,7 +6,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! The implementations of the `Standard` distribution for other built-in types. +//! The implementations of the `StandardUniform` distribution for other built-in types. #[cfg(feature = "alloc")] use alloc::string::String; @@ -15,7 +15,7 @@ use core::num::Wrapping; #[cfg(feature = "alloc")] use crate::distr::DistString; -use crate::distr::{Distribution, Standard, Uniform}; +use crate::distr::{Distribution, StandardUniform, Uniform}; use crate::Rng; use core::mem::{self, MaybeUninit}; @@ -72,7 +72,7 @@ pub struct Alphanumeric; // ----- Implementations of distributions ----- -impl Distribution for Standard { +impl Distribution for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> char { // A valid `char` is either in the interval `[0, 0xD800)` or @@ -96,7 +96,7 @@ impl Distribution for Standard { /// Note: the `String` is potentially left with excess capacity; optionally the /// user may call `string.shrink_to_fit()` afterwards. #[cfg(feature = "alloc")] -impl DistString for Standard { +impl DistString for StandardUniform { fn append_string(&self, rng: &mut R, s: &mut String, len: usize) { // A char is encoded with at most four bytes, thus this reservation is // guaranteed to be sufficient. We do not shrink_to_fit afterwards so @@ -135,7 +135,7 @@ impl DistString for Alphanumeric { } } -impl Distribution for Standard { +impl Distribution for StandardUniform { #[inline] fn sample(&self, rng: &mut R) -> bool { // We can compare against an arbitrary bit of an u32 to get a bool. @@ -173,11 +173,11 @@ impl Distribution for Standard { /// [`_mm_blendv_epi8`]: https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_blendv_epi8&ig_expand=514/ /// [`simd_support`]: https://github.com/rust-random/rand#crate-features #[cfg(feature = "simd_support")] -impl Distribution> for Standard +impl Distribution> for StandardUniform where T: MaskElement + Default, LaneCount: SupportedLaneCount, - Standard: Distribution>, + StandardUniform: Distribution>, Simd: SimdPartialOrd>, { #[inline] @@ -189,13 +189,13 @@ where } } -/// Implement `Distribution<(A, B, C, ...)> for Standard`, using the list of +/// Implement `Distribution<(A, B, C, ...)> for StandardUniform`, using the list of /// identifiers macro_rules! tuple_impl { ($($tyvar:ident)*) => { - impl< $($tyvar,)* > Distribution<($($tyvar,)*)> for Standard + impl< $($tyvar,)* > Distribution<($($tyvar,)*)> for StandardUniform where $( - Standard: Distribution< $tyvar >, + StandardUniform: Distribution< $tyvar >, )* { #[inline] @@ -234,9 +234,9 @@ macro_rules! tuple_impls { tuple_impls! {A B C D E F G H I J K L} -impl Distribution<[T; N]> for Standard +impl Distribution<[T; N]> for StandardUniform where - Standard: Distribution, + StandardUniform: Distribution, { #[inline] fn sample(&self, _rng: &mut R) -> [T; N] { @@ -250,9 +250,9 @@ where } } -impl Distribution> for Standard +impl Distribution> for StandardUniform where - Standard: Distribution, + StandardUniform: Distribution, { #[inline] fn sample(&self, rng: &mut R) -> Option { @@ -265,9 +265,9 @@ where } } -impl Distribution> for Standard +impl Distribution> for StandardUniform where - Standard: Distribution, + StandardUniform: Distribution, { #[inline] fn sample(&self, rng: &mut R) -> Wrapping { @@ -284,8 +284,8 @@ mod tests { fn test_misc() { let rng: &mut dyn RngCore = &mut crate::test::rng(820); - rng.sample::(Standard); - rng.sample::(Standard); + rng.sample::(StandardUniform); + rng.sample::(StandardUniform); } #[cfg(feature = "alloc")] @@ -333,7 +333,7 @@ mod tests { } test_samples( - &Standard, + &StandardUniform, 'a', &[ '\u{8cdac}', @@ -344,14 +344,14 @@ mod tests { ], ); test_samples(&Alphanumeric, 0, &[104, 109, 101, 51, 77]); - test_samples(&Standard, false, &[true, true, false, true, false]); + test_samples(&StandardUniform, false, &[true, true, false, true, false]); test_samples( - &Standard, + &StandardUniform, None as Option, &[Some(true), None, Some(false), None, Some(false)], ); test_samples( - &Standard, + &StandardUniform, Wrapping(0i32), &[ Wrapping(-2074640887), @@ -363,14 +363,14 @@ mod tests { ); // We test only sub-sets of tuple and array impls - test_samples(&Standard, (), &[(), (), (), (), ()]); + test_samples(&StandardUniform, (), &[(), (), (), (), ()]); test_samples( - &Standard, + &StandardUniform, (false,), &[(true,), (true,), (false,), (true,), (false,)], ); test_samples( - &Standard, + &StandardUniform, (false, false), &[ (true, true), @@ -381,9 +381,9 @@ mod tests { ], ); - test_samples(&Standard, [0u8; 0], &[[], [], [], [], []]); + test_samples(&StandardUniform, [0u8; 0], &[[], [], [], [], []]); test_samples( - &Standard, + &StandardUniform, [0u8; 3], &[ [9, 247, 111], diff --git a/src/distr/uniform.rs b/src/distr/uniform.rs index ac3e1676ad..81c1d7f07b 100644 --- a/src/distr/uniform.rs +++ b/src/distr/uniform.rs @@ -154,7 +154,7 @@ use serde::{Deserialize, Serialize}; /// When sampling from a constant range, many calculations can happen at /// compile-time and all methods should be fast; for floating-point ranges and /// the full range of integer types, this should have comparable performance to -/// the `Standard` distribution. +/// the `StandardUniform` distribution. /// /// # Provided implementations /// diff --git a/src/distr/uniform_float.rs b/src/distr/uniform_float.rs index 99bf2bf601..adcc7b710d 100644 --- a/src/distr/uniform_float.rs +++ b/src/distr/uniform_float.rs @@ -43,7 +43,7 @@ use serde::{Deserialize, Serialize}; /// /// [`new`]: UniformSampler::new /// [`new_inclusive`]: UniformSampler::new_inclusive -/// [`Standard`]: crate::distr::Standard +/// [`StandardUniform`]: crate::distr::StandardUniform /// [`Uniform`]: super::Uniform #[derive(Clone, Copy, Debug, PartialEq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] diff --git a/src/distr/uniform_int.rs b/src/distr/uniform_int.rs index 4fe07707bd..d5c56b02a0 100644 --- a/src/distr/uniform_int.rs +++ b/src/distr/uniform_int.rs @@ -12,7 +12,7 @@ use super::{Error, SampleBorrow, SampleUniform, UniformSampler}; use crate::distr::utils::WideningMultiply; #[cfg(feature = "simd_support")] -use crate::distr::{Distribution, Standard}; +use crate::distr::{Distribution, StandardUniform}; use crate::Rng; #[cfg(feature = "simd_support")] @@ -286,7 +286,7 @@ macro_rules! uniform_simd_int_impl { LaneCount: SupportedLaneCount, Simd<$unsigned, LANES>: WideningMultiply, Simd<$unsigned, LANES>)>, - Standard: Distribution>, + StandardUniform: Distribution>, { type Sampler = UniformInt>; } @@ -297,7 +297,7 @@ macro_rules! uniform_simd_int_impl { LaneCount: SupportedLaneCount, Simd<$unsigned, LANES>: WideningMultiply, Simd<$unsigned, LANES>)>, - Standard: Distribution>, + StandardUniform: Distribution>, { type X = Simd<$ty, LANES>; diff --git a/src/lib.rs b/src/lib.rs index f909292547..f8a7e6e92c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -119,14 +119,14 @@ pub fn thread_rng() -> crate::rngs::ThreadRng { pub use rng::{Fill, Rng}; #[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] -use crate::distr::{Distribution, Standard}; +use crate::distr::{Distribution, StandardUniform}; /// Generate a random value using the thread-local random number generator. /// /// This function is shorthand for [rng()].[random()](Rng::random): /// /// - See [`ThreadRng`] for documentation of the generator and security -/// - See [`Standard`] for documentation of supported types and distributions +/// - See [`StandardUniform`] for documentation of supported types and distributions /// /// # Examples /// @@ -157,13 +157,13 @@ use crate::distr::{Distribution, Standard}; /// } /// ``` /// -/// [`Standard`]: distr::Standard +/// [`StandardUniform`]: distr::StandardUniform /// [`ThreadRng`]: rngs::ThreadRng #[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] #[inline] pub fn random() -> T where - Standard: Distribution, + StandardUniform: Distribution, { rng().random() } @@ -181,9 +181,9 @@ where /// ``` #[cfg(all(feature = "std", feature = "std_rng", feature = "getrandom"))] #[inline] -pub fn random_iter() -> distr::DistIter +pub fn random_iter() -> distr::DistIter where - Standard: Distribution, + StandardUniform: Distribution, { rng().random_iter() } diff --git a/src/rng.rs b/src/rng.rs index 9ac481ed9c..04b71f74b7 100644 --- a/src/rng.rs +++ b/src/rng.rs @@ -10,7 +10,7 @@ //! [`Rng`] trait use crate::distr::uniform::{SampleRange, SampleUniform}; -use crate::distr::{self, Distribution, Standard}; +use crate::distr::{self, Distribution, StandardUniform}; use core::num::Wrapping; use rand_core::RngCore; use zerocopy::IntoBytes; @@ -56,7 +56,7 @@ use zerocopy::IntoBytes; /// # let v = foo(&mut rand::rng()); /// ``` pub trait Rng: RngCore { - /// Return a random value via the [`Standard`] distribution. + /// Return a random value via the [`StandardUniform`] distribution. /// /// # Example /// @@ -90,19 +90,19 @@ pub trait Rng: RngCore { /// rng.fill(&mut arr2); // array fill /// ``` /// - /// [`Standard`]: distr::Standard + /// [`StandardUniform`]: distr::StandardUniform #[inline] fn random(&mut self) -> T where - Standard: Distribution, + StandardUniform: Distribution, { - Standard.sample(self) + StandardUniform.sample(self) } /// Return an iterator over [`random`](Self::random) variates /// /// This is a just a wrapper over [`Rng::sample_iter`] using - /// [`distr::Standard`]. + /// [`distr::StandardUniform`]. /// /// Note: this method consumes its argument. Use /// `(&mut rng).random_iter()` to avoid consuming the RNG. @@ -117,12 +117,12 @@ pub trait Rng: RngCore { /// assert_eq!(&v, &[1, 2, 3, 4, 5]); /// ``` #[inline] - fn random_iter(self) -> distr::DistIter + fn random_iter(self) -> distr::DistIter where Self: Sized, - Standard: Distribution, + StandardUniform: Distribution, { - Standard.sample_iter(self) + StandardUniform.sample_iter(self) } /// Generate a random value in the given range. @@ -259,12 +259,12 @@ pub trait Rng: RngCore { /// /// ``` /// use rand::Rng; - /// use rand::distr::{Alphanumeric, Uniform, Standard}; + /// use rand::distr::{Alphanumeric, Uniform, StandardUniform}; /// /// let mut rng = rand::rng(); /// /// // Vec of 16 x f32: - /// let v: Vec = (&mut rng).sample_iter(Standard).take(16).collect(); + /// let v: Vec = (&mut rng).sample_iter(StandardUniform).take(16).collect(); /// /// // String: /// let s: String = (&mut rng).sample_iter(Alphanumeric) @@ -273,7 +273,7 @@ pub trait Rng: RngCore { /// .collect(); /// /// // Combined values - /// println!("{:?}", (&mut rng).sample_iter(Standard).take(5) + /// println!("{:?}", (&mut rng).sample_iter(StandardUniform).take(5) /// .collect::>()); /// /// // Dice-rolling: @@ -323,7 +323,7 @@ pub trait Rng: RngCore { )] fn r#gen(&mut self) -> T where - Standard: Distribution, + StandardUniform: Distribution, { self.random() } @@ -580,25 +580,25 @@ mod test { #[test] fn test_rng_trait_object() { - use crate::distr::{Distribution, Standard}; + use crate::distr::{Distribution, StandardUniform}; let mut rng = rng(109); let mut r = &mut rng as &mut dyn RngCore; r.next_u32(); r.random::(); assert_eq!(r.random_range(0..1), 0); - let _c: u8 = Standard.sample(&mut r); + let _c: u8 = StandardUniform.sample(&mut r); } #[test] #[cfg(feature = "alloc")] fn test_rng_boxed_trait() { - use crate::distr::{Distribution, Standard}; + use crate::distr::{Distribution, StandardUniform}; let rng = rng(110); let mut r = Box::new(rng) as Box; r.next_u32(); r.random::(); assert_eq!(r.random_range(0..1), 0); - let _c: u8 = Standard.sample(&mut r); + let _c: u8 = StandardUniform.sample(&mut r); } #[test] diff --git a/src/rngs/mock.rs b/src/rngs/mock.rs index dc0bd764a6..b6da66a856 100644 --- a/src/rngs/mock.rs +++ b/src/rngs/mock.rs @@ -93,11 +93,11 @@ mod tests { #[test] #[cfg(feature = "alloc")] fn test_bool() { - use crate::{distr::Standard, Rng}; + use crate::{distr::StandardUniform, Rng}; // If this result ever changes, update doc on StepRng! let rng = StepRng::new(0, 1 << 31); - let result: alloc::vec::Vec = rng.sample_iter(Standard).take(6).collect(); + let result: alloc::vec::Vec = rng.sample_iter(StandardUniform).take(6).collect(); assert_eq!(&result, &[false, true, false, true, false, true]); } } From 9816a7cde955fdeb671040a722c2ecf563166326 Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 12 Nov 2024 17:38:11 +0000 Subject: [PATCH 2/7] Remove Option support for StandardUniform --- src/distr/mod.rs | 2 -- src/distr/other.rs | 20 -------------------- src/lib.rs | 3 +-- 3 files changed, 1 insertion(+), 24 deletions(-) diff --git a/src/distr/mod.rs b/src/distr/mod.rs index 1565305f79..4883312c09 100644 --- a/src/distr/mod.rs +++ b/src/distr/mod.rs @@ -162,8 +162,6 @@ use crate::Rng; /// the former is optimised for integer types (using fewer RNG calls for /// element types smaller than the RNG word size), while the latter supports /// any element type supported by `StandardUniform`. -/// * `Option` first generates a `bool`, and if true generates and returns -/// `Some(value)` where `value: T`, otherwise returning `None`. /// /// ## Custom implementations /// diff --git a/src/distr/other.rs b/src/distr/other.rs index 6b6c6c24f3..8e957f0744 100644 --- a/src/distr/other.rs +++ b/src/distr/other.rs @@ -250,21 +250,6 @@ where } } -impl Distribution> for StandardUniform -where - StandardUniform: Distribution, -{ - #[inline] - fn sample(&self, rng: &mut R) -> Option { - // UFCS is needed here: https://github.com/rust-lang/rust/issues/24066 - if rng.random::() { - Some(rng.random()) - } else { - None - } - } -} - impl Distribution> for StandardUniform where StandardUniform: Distribution, @@ -345,11 +330,6 @@ mod tests { ); test_samples(&Alphanumeric, 0, &[104, 109, 101, 51, 77]); test_samples(&StandardUniform, false, &[true, true, false, true, false]); - test_samples( - &StandardUniform, - None as Option, - &[Some(true), None, Some(false), None, Some(false)], - ); test_samples( &StandardUniform, Wrapping(0i32), diff --git a/src/lib.rs b/src/lib.rs index f8a7e6e92c..5b410ca8cb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -306,11 +306,10 @@ mod test { fn test_random() { let _n: u64 = random(); let _f: f32 = random(); - let _o: Option> = random(); #[allow(clippy::type_complexity)] let _many: ( (), - Option<(u32, (bool,))>, + [(u32, bool); 3], (u8, i8, u16, i16, u32, i32, u64, i64), (f32, (f64, (f64,))), ) = random(); From 35afe7f1de521552bd03bfd71b14e2d8f78c0e00 Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 12 Nov 2024 17:59:49 +0000 Subject: [PATCH 3/7] Revise docs --- src/distr/mod.rs | 77 +++++++++++++++++++------------------------- src/distr/uniform.rs | 2 +- 2 files changed, 34 insertions(+), 45 deletions(-) diff --git a/src/distr/mod.rs b/src/distr/mod.rs index 4883312c09..d01d2e8493 100644 --- a/src/distr/mod.rs +++ b/src/distr/mod.rs @@ -28,7 +28,7 @@ //! [`Uniform`] allows specification of its sample space as a range within `T`). //! //! -//! # The `StandardUniform` distribution +//! # The Standard Uniform distribution //! //! The [`StandardUniform`] distribution is important to mention. This is the //! distribution used by [`Rng::random`] and represents the "default" way to @@ -36,42 +36,33 @@ //! types, tuples, arrays, and a few derived types. See the documentation of //! [`StandardUniform`] for more details. //! -//! Implementing `Distribution` for [`StandardUniform`] for user types `T` makes it +//! Implementing [`Distribution`] for [`StandardUniform`] for user types `T` makes it //! possible to generate type `T` with [`Rng::random`], and by extension also //! with the [`random`] function. //! -//! ## Random characters +//! ## Other standard uniform distributions //! //! [`Alphanumeric`] is a simple distribution to sample random letters and //! numbers of the `char` type; in contrast [`StandardUniform`] may sample any valid //! `char`. //! +//! For floats (`f32`, `f64`), [`StandardUniform`] samples from `[0, 1)`. Also +//! provided are [`Open01`] (samples from `(0, 1)`) and [`OpenClosed01`] +//! (samples from `(0, 1]`). No option is provided to sample from `[0, 1]`; it +//! is suggested to use one of the above half-open ranges since the failure to +//! sample a value which would have a low chance of being sampled anyway is +//! rarely an issue in practice. //! -//! # Uniform numeric ranges +//! # Parameterized Uniform distributions //! -//! The [`Uniform`] distribution is more flexible than [`StandardUniform`], but also -//! more specialised: it supports fewer target types, but allows the sample -//! space to be specified as an arbitrary range within its target type `T`. -//! Both [`StandardUniform`] and [`Uniform`] are in some sense uniform distributions. +//! The [`Uniform`] distribution provides uniform sampling over a specified +//! range on a subset of the types supported by the above distributions. //! -//! Values may be sampled from this distribution using [`Rng::sample(Range)`] or -//! by creating a distribution object with [`Uniform::new`], -//! [`Uniform::new_inclusive`] or `From`. When the range limits are not -//! known at compile time it is typically faster to reuse an existing -//! `Uniform` object than to call [`Rng::sample(Range)`]. -//! -//! User types `T` may also implement `Distribution` for [`Uniform`], -//! although this is less straightforward than for [`StandardUniform`] (see the -//! documentation in the [`uniform`] module). Doing so enables generation of -//! values of type `T` with [`Rng::sample(Range)`]. -//! -//! ## Open and half-open ranges -//! -//! There are surprisingly many ways to uniformly generate random floats. A -//! range between 0 and 1 is standard, but the exact bounds (open vs closed) -//! and accuracy differ. In addition to the [`StandardUniform`] distribution Rand offers -//! [`Open01`] and [`OpenClosed01`]. See "Floating point implementation" section of -//! [`StandardUniform`] documentation for more details. +//! Implementations support single-value-sampling via +//! [`Rng::random_range(Range)`](Rng::random_range). +//! Where a fixed (non-`const`) range will be sampled many times, it is likely +//! faster to pre-construct a [`Distribution`] object using +//! [`Uniform::new`], [`Uniform::new_inclusive`] or `From`. //! //! # Non-uniform sampling //! @@ -124,28 +115,29 @@ pub use self::weighted_index::{Weight, WeightError, WeightedIndex}; #[allow(unused)] use crate::Rng; -/// A generic random value distribution, implemented for many primitive types. -/// Usually generates values with a numerically uniform distribution, and with a -/// range appropriate to the type. +/// The Standard Uniform distribution /// -/// ## Provided implementations +/// This [`Distribution`] is the *standard* parameterization of [`Uniform`]. Bounds +/// are selected according to the output type. /// /// Assuming the provided `Rng` is well-behaved, these implementations /// generate values with the following ranges and distributions: /// -/// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed -/// over all values of the type. -/// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all +/// * Integers (`i8`, `i32`, `u64`, etc.) are uniformly distributed +/// over the whole range of the type (thus each possible value may be sampled +/// with equal probability). +/// * `char` is uniformly distributed over all Unicode scalar values, i.e. all /// code points in the range `0...0x10_FFFF`, except for the range /// `0xD800...0xDFFF` (the surrogate code points). This includes /// unassigned/reserved code points. -/// * `bool`: Generates `false` or `true`, each with probability 0.5. -/// * Floating point types (`f32` and `f64`): Uniformly distributed in the -/// half-open range `[0, 1)`. See notes below. +/// For some uses, the [`Alphanumeric`] distribution will be more appropriate. +/// * `bool` samples `false` or `true`, each with probability 0.5. +/// * Floating point types (`f32` and `f64`) are uniformly distributed in the +/// half-open range `[0, 1)`. See also the [notes below](#floating-point-implementation). /// * Wrapping integers ([`Wrapping`]), besides the type identical to their /// normal integer variants. /// * Non-zero integers ([`NonZeroU8`]), which are like their normal integer -/// variants but cannot produce zero. +/// variants but cannot sample zero. /// * SIMD types like x86's [`__m128i`], `std::simd`'s [`u32x4`]/[`f32x4`]/ /// [`mask32x4`] (requires [`simd_support`]), where each lane is distributed /// like their scalar `StandardUniform` variants. See the list of `StandardUniform` @@ -155,13 +147,10 @@ use crate::Rng; /// compound types where all component types are supported: /// /// * Tuples (up to 12 elements): each element is generated sequentially. -/// * Arrays: each element is generated sequentially; -/// see also [`Rng::fill`] which supports arbitrary array length for integer -/// and float types and tends to be faster for `u32` and smaller types. -/// Note that [`Rng::fill`] and `StandardUniform`'s array support are *not* equivalent: -/// the former is optimised for integer types (using fewer RNG calls for -/// element types smaller than the RNG word size), while the latter supports -/// any element type supported by `StandardUniform`. +/// * Arrays `[T; n]` where `T` is supported. Each element is generated +/// sequentially which is sub-optimal where `T` is small; it may be faster +/// to [`Rng::fill`] an existing array (but note that the two methods do not +/// necessarily yield the same values). /// /// ## Custom implementations /// diff --git a/src/distr/uniform.rs b/src/distr/uniform.rs index 81c1d7f07b..f396422d64 100644 --- a/src/distr/uniform.rs +++ b/src/distr/uniform.rs @@ -154,7 +154,7 @@ use serde::{Deserialize, Serialize}; /// When sampling from a constant range, many calculations can happen at /// compile-time and all methods should be fast; for floating-point ranges and /// the full range of integer types, this should have comparable performance to -/// the `StandardUniform` distribution. +/// the [`StandardUniform`](super::StandardUniform) distribution. /// /// # Provided implementations /// From 19399f256a11de36e40367ba7ce6b3c0c6c0d8b7 Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Tue, 12 Nov 2024 18:00:53 +0000 Subject: [PATCH 4/7] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71c7353174..96a0bf9031 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update. - 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 `Uniform` to `StandardUniform` (#1526) ## [0.9.0-alpha.1] - 2024-03-18 - Add the `Slice::num_choices` method to the Slice distribution (#1402) From 0d88a548eb6296fc6c7250aa17eeb163f9867900 Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Wed, 13 Nov 2024 11:11:22 +0000 Subject: [PATCH 5/7] Update SIMD docs --- src/distr/mod.rs | 23 ++++++++++++++--------- src/distr/uniform.rs | 10 ++++++++++ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/distr/mod.rs b/src/distr/mod.rs index d01d2e8493..9ee932417f 100644 --- a/src/distr/mod.rs +++ b/src/distr/mod.rs @@ -138,19 +138,24 @@ use crate::Rng; /// normal integer variants. /// * Non-zero integers ([`NonZeroU8`]), which are like their normal integer /// variants but cannot sample zero. -/// * SIMD types like x86's [`__m128i`], `std::simd`'s [`u32x4`]/[`f32x4`]/ -/// [`mask32x4`] (requires [`simd_support`]), where each lane is distributed -/// like their scalar `StandardUniform` variants. See the list of `StandardUniform` -/// implementations for more. /// /// The `StandardUniform` distribution also supports generation of the following /// compound types where all component types are supported: /// -/// * Tuples (up to 12 elements): each element is generated sequentially. -/// * Arrays `[T; n]` where `T` is supported. Each element is generated -/// sequentially which is sub-optimal where `T` is small; it may be faster -/// to [`Rng::fill`] an existing array (but note that the two methods do not -/// necessarily yield the same values). +/// * Tuples (up to 12 elements): each element is sampled sequentially and +/// independently (thus, assuming a well-behaved RNG, there is no correlation +/// between elements). +/// * Arrays `[T; n]` where `T` is supported. Each element is sampled +/// sequentially and independently. Note that for small `T` this usually +/// results in the RNG discarding random bits; see also [`Rng::fill`] which +/// offers a more efficient approach to filling an array of integer types +/// with random data. +/// * SIMD types (requires [`simd_support`] feature) like x86's [`__m128i`] +/// and `std::simd`'s [`u32x4`], [`f32x4`] and [`mask32x4`] types are +/// effectively arrays of integer or floating-point types. Each lane is +/// sampled independently, potentially with more efficient random-bit-usage +/// (and a different resulting value) than would be achieved with sequential +/// sampling (as with the array types above). /// /// ## Custom implementations /// diff --git a/src/distr/uniform.rs b/src/distr/uniform.rs index f396422d64..b59fdbf790 100644 --- a/src/distr/uniform.rs +++ b/src/distr/uniform.rs @@ -173,6 +173,11 @@ use serde::{Deserialize, Serialize}; /// 64-bit CPU architectures. /// - `Duration` ([`UniformDuration`]): samples a range over the implementation /// for `u32` or `u64` +/// - SIMD types (requires [`simd_support`] feature) like x86's [`__m128i`] +/// and `std::simd`'s [`u32x4`], [`f32x4`] and [`mask32x4`] types are +/// effectively arrays of integer or floating-point types. Each lane is +/// sampled independently from its own range, potentially with more efficient +/// random-bit-usage than would be achieved with sequential sampling. /// /// # Example /// @@ -200,6 +205,11 @@ use serde::{Deserialize, Serialize}; /// [`new`]: Uniform::new /// [`new_inclusive`]: Uniform::new_inclusive /// [`Rng::random_range`]: Rng::random_range +/// [`__m128i`]: https://doc.rust-lang.org/core/arch/x86/struct.__m128i.html +/// [`u32x4`]: std::simd::u32x4 +/// [`f32x4`]: std::simd::f32x4 +/// [`mask32x4`]: std::simd::mask32x4 +/// [`simd_support`]: https://github.com/rust-random/rand#crate-features #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serde", serde(bound(serialize = "X::Sampler: Serialize")))] From 8de36356a37c808d9f27adfcbde0f23a60d3193c Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Mon, 18 Nov 2024 15:58:03 +0000 Subject: [PATCH 6/7] CHANGELOG: removal of Option impl --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96a0bf9031..685d4c71f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update. - 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 `Uniform` to `StandardUniform` (#1526) +- Remove impl of `Distribution>` for `Standard` (#1526) ## [0.9.0-alpha.1] - 2024-03-18 - Add the `Slice::num_choices` method to the Slice distribution (#1402) From e7cba1db0339c112135536af2e41616c2d703bfe Mon Sep 17 00:00:00 2001 From: Diggory Hardy Date: Mon, 18 Nov 2024 16:05:13 +0000 Subject: [PATCH 7/7] CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 685d4c71f8..44603eeb53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,7 @@ You may also find the [Upgrade Guide](https://rust-random.github.io/book/update. - 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 `Uniform` to `StandardUniform` (#1526) +- Rename `Standard` to `StandardUniform` (#1526) - Remove impl of `Distribution>` for `Standard` (#1526) ## [0.9.0-alpha.1] - 2024-03-18