rand_distr::uniform

Struct Uniform

Source
pub struct Uniform<X>(/* private fields */)
where
    X: SampleUniform;
Expand description

Sample values uniformly between two bounds.

§Construction

Uniform::new and Uniform::new_inclusive construct a uniform distribution sampling from the given low and high limits. Uniform may also be constructed via TryFrom as in Uniform::try_from(1..=6).unwrap().

Constructors may do extra work up front to allow faster sampling of multiple values. Where only a single sample is required it is suggested to use Rng::random_range or one of the sample_single methods instead.

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.

§Provided implementations

  • char (UniformChar): samples a range over the implementation for u32
  • f32, f64 (UniformFloat): samples approximately uniformly within a range; bias may be present in the least-significant bit of the significand and the limits of the input range may be sampled even when an open (exclusive) range is used
  • Integer types (UniformInt) may show a small bias relative to the expected uniform distribution of output. In the worst case, bias affects 1 in 2^n samples where n is 56 (i8 and u8), 48 (i16 and u16), 96 (i32 and u32), 64 (i64 and u64), 128 (i128 and u128). The unbiased feature flag fixes this bias.
  • usize (UniformUsize) is handled specially, using the u32 implementation where possible to enable portable results across 32-bit and 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

use rand::distr::{Distribution, Uniform};

let between = Uniform::try_from(10..10000).unwrap();
let mut rng = rand::rng();
let mut sum = 0;
for _ in 0..1000 {
    sum += between.sample(&mut rng);
}
println!("{}", sum);

For a single sample, Rng::random_range may be preferred:

use rand::Rng;

let mut rng = rand::rng();
println!("{}", rng.random_range(0..10));

Implementations§

Source§

impl<X> Uniform<X>
where X: SampleUniform,

Source

pub fn new<B1, B2>(low: B1, high: B2) -> Result<Uniform<X>, Error>
where B1: SampleBorrow<X>, B2: SampleBorrow<X>,

Create a new Uniform instance, which samples uniformly from the half open range [low, high) (excluding high).

For discrete types (e.g. integers), samples will always be strictly less than high. For (approximations of) continuous types (e.g. f32, f64), samples may equal high due to loss of precision but may not be greater than high.

Fails if low >= high, or if low, high or the range high - low is non-finite. In release mode, only the range is checked.

Source

pub fn new_inclusive<B1, B2>(low: B1, high: B2) -> Result<Uniform<X>, Error>
where B1: SampleBorrow<X>, B2: SampleBorrow<X>,

Create a new Uniform instance, which samples uniformly from the closed range [low, high] (inclusive).

Fails if low > high, or if low, high or the range high - low is non-finite. In release mode, only the range is checked.

Trait Implementations§

Source§

impl<X> Clone for Uniform<X>

Source§

fn clone(&self) -> Uniform<X>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<X> Debug for Uniform<X>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<'de, X> Deserialize<'de> for Uniform<X>

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<Uniform<X>, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl DistString for Uniform<char>

Note: the String is potentially left with excess capacity if the range includes non ascii chars; optionally the user may call string.shrink_to_fit() afterwards.

Source§

fn append_string<R>(&self, rng: &mut R, string: &mut String, len: usize)
where R: Rng + ?Sized,

Append len random chars to string
Source§

fn sample_string<R>(&self, rng: &mut R, len: usize) -> String
where R: Rng + ?Sized,

Generate a String of len random chars
Source§

impl<X> Distribution<X> for Uniform<X>
where X: SampleUniform,

Source§

fn sample<R>(&self, rng: &mut R) -> X
where R: Rng + ?Sized,

Generate a random value of T, using rng as the source of randomness.
Source§

fn sample_iter<R>(self, rng: R) -> DistIter<Self, R, T>
where R: Rng, Self: Sized,

Create an iterator that generates random values of T, using rng as the source of randomness. Read more
Source§

fn map<F, S>(self, func: F) -> DistMap<Self, F, T, S>
where F: Fn(T) -> S, Self: Sized,

Create a distribution of values of ‘S’ by mapping the output of Self through the closure F Read more
Source§

impl<X> PartialEq for Uniform<X>

Source§

fn eq(&self, other: &Uniform<X>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<X> Serialize for Uniform<X>

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<X> TryFrom<Range<X>> for Uniform<X>
where X: SampleUniform,

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(r: Range<X>) -> Result<Uniform<X>, Error>

Performs the conversion.
Source§

impl<X> TryFrom<RangeInclusive<X>> for Uniform<X>
where X: SampleUniform,

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(r: RangeInclusive<X>) -> Result<Uniform<X>, Error>

Performs the conversion.
Source§

impl<X> Copy for Uniform<X>

Source§

impl<X> Eq for Uniform<X>
where X: Eq + SampleUniform, <X as SampleUniform>::Sampler: Eq,

Source§

impl<X> StructuralPartialEq for Uniform<X>
where X: SampleUniform,

Auto Trait Implementations§

§

impl<X> Freeze for Uniform<X>
where <X as SampleUniform>::Sampler: Freeze,

§

impl<X> RefUnwindSafe for Uniform<X>

§

impl<X> Send for Uniform<X>
where <X as SampleUniform>::Sampler: Send,

§

impl<X> Sync for Uniform<X>
where <X as SampleUniform>::Sampler: Sync,

§

impl<X> Unpin for Uniform<X>
where <X as SampleUniform>::Sampler: Unpin,

§

impl<X> UnwindSafe for Uniform<X>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,