Debian Codegraph @

debian/rust-vendor/rand/src/distr/mod.rs

raw
1 // Copyright 2018 Developers of the Rand project.
2 // Copyright 2013-2017 The Rust Project Developers.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 //! Generating random samples from probability distributions
11 //!
12 //! # Quick start
13 //!
14 //! ```
15 //! use rand::RngExt;
16 //! let mut rng = rand::rng();
17 //!
18 //! eprintln!("A letter: {}", rng.sample(rand::distr::Alphabetic) as char);
19 //!
20 //! let percent_range = rand::distr::Uniform::try_from(0..=100).unwrap();
21 //! eprintln!("Percentage: {}%", rng.sample(&percent_range));
22 //! ```
23 //!
24 //! # `Distribution` trait
25 //!
26 //! Abstractly, a [probability distribution] describes the probability of
27 //! occurrence of each value in its sample space.
28 //!
29 //! More concretely, a sampler `X` implementing
30 //! <code>[Distribution][]&lt;T&gt;</code> is an algorithm for choosing values
31 //! from the sample space `T` (or a subset of `T`) using randomness from an
32 //! [`Rng`].
33 //! Typically the sampler `X` emulates some like-named probability distribution
34 //! (for example, [`Bernoulli`] emulates the
35 //! [Bernoulli distribution](https://en.wikipedia.org/wiki/Bernoulli_distribution)).
36 //!
37 //! ## The Standard Uniform distribution
38 //!
39 //! The [`StandardUniform`] distribution is perhaps the most important sampler,
40 //! representing the "default" probability distribution for a type.
41 //! Its distribution is expected to be uniform. For `bool`, `char` and integer
42 //! types the sample space equals that of the type (i.e. any valid value of that
43 //! type may be yielded), but for floating-point types the sample range is
44 //! arbitrarily set to `0.0..1.0`.
45 //!
46 //! Implementing [`Distribution<T>`] for [`StandardUniform`] for type `T`
47 //! enables sampling type `T` using [`RngExt::random`] and (by extension)
48 //! [`rand::random`].
49 //!
50 //! ### Other standard uniform distributions
51 //!
52 //! [`Alphanumeric`] is a simple distribution to sample random letters and
53 //! numbers of the `char` type; in contrast [`StandardUniform`] may sample any valid
54 //! `char`.
55 //!
56 //! There's also an [`Alphabetic`] distribution which acts similarly to [`Alphanumeric`] but
57 //! doesn't include digits.
58 //!
59 //! For floats (`f32`, `f64`), [`StandardUniform`] samples from `[0, 1)`. Also
60 //! provided are [`Open01`] (samples from `(0, 1)`) and [`OpenClosed01`]
61 //! (samples from `(0, 1]`). No option is provided to sample from `[0, 1]`; it
62 //! is suggested to use one of the above half-open ranges since the failure to
63 //! sample a value which would have a low chance of being sampled anyway is
64 //! rarely an issue in practice.
65 //!
66 //! ## Parameterized Uniform distributions
67 //!
68 //! The [`Uniform`] distribution provides uniform sampling over a specified
69 //! range on a subset of the types supported by the above distributions.
70 //!
71 //! Implementations support single-value-sampling via
72 //! [`Rng::random_range(Range)`](RngExt::random_range).
73 //! Where a fixed (non-`const`) range will be sampled many times, it is likely
74 //! faster to pre-construct a [`Distribution`] object using
75 //! [`Uniform::new`], [`Uniform::new_inclusive`] or `From<Range>`.
76 //!
77 //! ## Non-uniform sampling
78 //!
79 //! Sampling a simple true/false outcome with a given probability has a name:
80 //! the [`Bernoulli`] distribution (this is used by [`RngExt::random_bool`]).
81 //!
82 //! For weighted sampling of discrete values see the [`weighted`] module.
83 //!
84 //! This crate no longer includes other non-uniform distributions; instead
85 //! it is recommended that you use either [`rand_distr`] or [`statrs`].
86 //!
87 //!
88 //! [probability distribution]: https://en.wikipedia.org/wiki/Probability_distribution
89 //! [`rand_distr`]: https://crates.io/crates/rand_distr
90 //! [`statrs`]: https://crates.io/crates/statrs
91 //! [`rand::random`]: crate::random
92 //! [`rand_distr`]: https://crates.io/crates/rand_distr
93 //! [`statrs`]: https://crates.io/crates/statrs
94 //! [`Rng`]: crate::Rng
95
96 mod bernoulli;
97 mod distribution;
98 mod float;
99 mod integer;
100 mod other;
101 mod utils;
102
103 #[doc(hidden)]
104 pub mod hidden_export {
105 pub use super::float::IntoFloat; // used by rand_distr
106 }
107 pub mod slice;
108 pub mod uniform;
109 #[cfg(feature = "alloc")]
110 pub mod weighted;
111
112 pub use self::bernoulli::{Bernoulli, BernoulliError};
113 #[cfg(feature = "alloc")]
114 pub use self::distribution::SampleString;
115 pub use self::distribution::{Distribution, Iter, Map};
116 pub use self::float::{Open01, OpenClosed01};
117 pub use self::other::{Alphabetic, Alphanumeric};
118 #[doc(inline)]
119 pub use self::uniform::Uniform;
120
121 #[allow(unused)]
122 use crate::RngExt;
123
124 /// The Standard Uniform distribution
125 ///
126 /// This [`Distribution`] is the *standard* parameterization of [`Uniform`]. Bounds
127 /// are selected according to the output type.
128 ///
129 /// Assuming the provided `Rng` is well-behaved, these implementations
130 /// generate values with the following ranges and distributions:
131 ///
132 /// * Integers (`i8`, `i32`, `u64`, etc.) are uniformly distributed
133 /// over the whole range of the type (thus each possible value may be sampled
134 /// with equal probability).
135 /// * `char` is uniformly distributed over all Unicode scalar values, i.e. all
136 /// code points in the range `0...0x10_FFFF`, except for the range
137 /// `0xD800...0xDFFF` (the surrogate code points). This includes
138 /// unassigned/reserved code points.
139 /// For some uses, the [`Alphanumeric`] or [`Alphabetic`] distribution will be more
140 /// appropriate.
141 /// * `bool` samples `false` or `true`, each with probability 0.5.
142 /// * Floating point types (`f32` and `f64`) are uniformly distributed in the
143 /// half-open range `[0, 1)`. See also the [notes below](#floating-point-implementation).
144 /// * Wrapping integers ([`Wrapping<T>`]), besides the type identical to their
145 /// normal integer variants.
146 /// * Non-zero integers ([`NonZeroU8`]), which are like their normal integer
147 /// variants but cannot sample zero.
148 ///
149 /// The `StandardUniform` distribution also supports generation of the following
150 /// compound types where all component types are supported:
151 ///
152 /// * Tuples (up to 12 elements): each element is sampled sequentially and
153 /// independently (thus, assuming a well-behaved RNG, there is no correlation
154 /// between elements).
155 /// * Arrays `[T; n]` where `T` is supported. Each element is sampled
156 /// sequentially and independently. Note that for small `T` this usually
157 /// results in the RNG discarding random bits; see also [`RngExt::fill`] which
158 /// offers a more efficient approach to filling an array of integer types
159 /// with random data.
160 /// * SIMD types (requires [`simd_support`] feature) like x86's [`__m128i`]
161 /// and `std::simd`'s [`u32x4`], [`f32x4`] and [`mask32x4`] types are
162 /// effectively arrays of integer or floating-point types. Each lane is
163 /// sampled independently, potentially with more efficient random-bit-usage
164 /// (and a different resulting value) than would be achieved with sequential
165 /// sampling (as with the array types above).
166 ///
167 /// ## Custom implementations
168 ///
169 /// The [`StandardUniform`] distribution may be implemented for user types as follows:
170 ///
171 /// ```
172 /// # #![allow(dead_code)]
173 /// use rand::{Rng, RngExt};
174 /// use rand::distr::{Distribution, StandardUniform};
175 ///
176 /// struct MyF32 {
177 /// x: f32,
178 /// }
179 ///
180 /// impl Distribution<MyF32> for StandardUniform {
181 /// fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MyF32 {
182 /// MyF32 { x: rng.random() }
183 /// }
184 /// }
185 /// ```
186 ///
187 /// ## Example usage
188 /// ```
189 /// use rand::prelude::*;
190 /// use rand::distr::StandardUniform;
191 ///
192 /// let val: f32 = rand::rng().sample(StandardUniform);
193 /// println!("f32 from [0, 1): {}", val);
194 /// ```
195 ///
196 /// # Floating point implementation
197 /// The floating point implementations for `StandardUniform` generate a random value in
198 /// the half-open interval `[0, 1)`, i.e. including 0 but not 1.
199 ///
200 /// All values that can be generated are of the form `n * ε/2`. For `f32`
201 /// the 24 most significant random bits of a `u32` are used and for `f64` the
202 /// 53 most significant bits of a `u64` are used. The conversion uses the
203 /// multiplicative method: `(rng.gen::<$uty>() >> N) as $ty * (ε/2)`.
204 ///
205 /// See also: [`Open01`] which samples from `(0, 1)`, [`OpenClosed01`] which
206 /// samples from `(0, 1]` and `Rng::random_range(0..1)` which also samples from
207 /// `[0, 1)`. Note that `Open01` uses transmute-based methods which yield 1 bit
208 /// less precision but may perform faster on some architectures (on modern Intel
209 /// CPUs all methods have approximately equal performance).
210 ///
211 /// [`Uniform`]: uniform::Uniform
212 /// [`Wrapping<T>`]: std::num::Wrapping
213 /// [`NonZeroU8`]: std::num::NonZeroU8
214 /// [`__m128i`]: https://doc.rust-lang.org/core/arch/x86/struct.__m128i.html
215 /// [`u32x4`]: std::simd::u32x4
216 /// [`f32x4`]: std::simd::f32x4
217 /// [`mask32x4`]: std::simd::mask32x4
218 /// [`simd_support`]: https://github.com/rust-random/rand#crate-features
219 #[derive(Clone, Copy, Debug, Default)]
220 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
221 pub struct StandardUniform;