std::random
本页内容
API 参考只有英文版,由标准库源代码中的英文文档注释生成。
cryptographically secure random bytes from the OS
(getrandom on Linux, getentropy on macOS, BCryptGenRandom on
Windows, random_get on WASI), seedable generators (Rng) with
ranges of any integer type and the common distributions, and one-call
forms over a shared generator. A failing OS source is not
recoverable: it panics. The algorithms that use the bytes are
core::crypto.
Structs
Xoshiro256PlusPlusSource
pub struct Xoshiro256PlusPlusXoshiro256++ (Blackman and Vigna; Julia's default): 256 bits of
state, period 2^256 - 1. Fast and statistically strong, not for
secrets (use the OS source: random::bytes, OsRng).
The generator for
seed: its state is four outputs of SplitMix64 started atseed. The same seed gives the same stream on every target and release.A generator seeded from the OS source: a different stream each time.
A generator for another stream, for a parallel task: a copy of this one, which then jumps 2^128 steps ahead (Vigna's
jump), so the two never overlap in practice. The streams depend only on the seed and the order of the calls, not on threads or timing.
Trait implementations 1
impl Rng for Xoshiro256PlusPlus
OsRngSource
pub struct OsRngThe OS source as an Rng: every value read from it (a system call
each), never reproducible.
Trait implementations 1
impl Rng for OsRng
Traits
RngSource
pub trait RngA source of random u64s and the values derived from them.
The next 64 random bits.
A value in
[0, 1): the top 53 bits ofnext_u64times 2^-53. Python:random.random().A value in
[0, n), every one equally likely (bits below the last whole multiple ofnare drawn again). Panics whennis 0.A value in
[0, 1): the top 24 bits ofnext_u64times 2^-24.
Sourceconst fn range<R: SampleRange>(§ref self, r: R) -> R::Item A value of
r, every one equally likely: a range of any integer type (0..6,1..=6,0u8..=255,0usize..n). Panics whenris empty. Python:random.randrange(a, b)/random.randint(a, b); for floats,uniform.nabiuse std::random::{Rng, Xoshiro256PlusPlus}; let g = Xoshiro256PlusPlus::seed(1); let die = g.range(1..=6); let i = g.range(0usize..10); let x = g.uniform(-1.0, 1.0); assert(die >= 1 && die <= 6 && i < 10 && x >= -1.0 && x < 1.0);A value in
[lo, hi):lo + (hi - lo) * self.f64(). Python:random.uniform(lo, hi).truewith probabilityp(self.f64() < p).A normal deviate with mean
meanand standard deviationstd(the ziggurat of Marsaglia and Tsang: one 64-bit draw nearly always). Python:random.gauss(mean, std).An exponential deviate with rate
rate(mean1 / rate):-ln(U) / rate. Python:random.expovariate(rate).A gamma deviate of shape
shapeand scalescale(meanshape * scale). Python:random.gammavariate(shape, scale).A beta deviate in
[0, 1]with shapesaandb. Python:random.betavariate(a, b).A Poisson count with mean
lam(lam >= 0). NumPy:rng.poisson(lam).The number of successes in
ntrials of probabilityp. NumPy:rng.binomial(n, p).nabiuse std::random::{Rng, Xoshiro256PlusPlus}; let g = Xoshiro256PlusPlus::seed(7); let k = g.binomial(10, 0.5); assert(k >= 0 && k <= 10 && g.poisson(3.0) >= 0); assert(g.gamma(2.0) > 0.0 && g.exponential() > 0.0); let b = g.beta(2.0, 5.0); assert(b >= 0.0 && b <= 1.0);An index of
weights,iwith probabilityweights[i] / sum. Panics for a negative or non-finite weight, or when all are 0. Python:random.choices(range(n), weights)[0].nabiuse std::random::{Rng, Xoshiro256PlusPlus}; let g = Xoshiro256PlusPlus::seed(3); let i = g.weighted([0.0, 1.0, 0.0]); assert(i == 1);Fill
outwith values in[0, 1)(f64each).Fill
outwith normal deviates (normaleach).An array of
shapewith values in[0, 1). NumPy:rng.random(shape).nabiuse std::random::{Rng, Xoshiro256PlusPlus}; let g = Xoshiro256PlusPlus::seed(5); let a = g.random_array([2, 3]); let z = g.normal_array([1000], mean: 10.0); assert(a.shape() == [2, 3] && (z.mean() - 10.0).abs() < 0.2);
Sourceconst fn normal_array<const N: usize>(§ref self, shape: [usize; N], mean: f64 = 0.0, std: f64 = 1.0) -> Array<f64, N> An array of
shapeof normal deviates. NumPy:rng.normal(mean, std, shape).
Sourceconst fn uniform_array<const N: usize>(§ref self, shape: [usize; N], lo: f64, hi: f64) -> Array<f64, N> An array of
shapewith values in[lo, hi). NumPy:rng.uniform(lo, hi, shape).The items of
xsin a random order, in place (Fisher-Yates from the back: positioniswaps withbelow(i + 1)).One item of
xs(xs[below(len)]), ornonewhen it is empty. Python:random.choice(xs).kitems ofxsat distinct positions, in the order drawn (a partial Fisher-Yates over the positions). Panics whenkis more thanxs.len(). Python:random.sample(xs, k).
SampleRangeSource
pub trait SampleRangeA range Rng::range draws from: a..b and a..=b of every
integer type. For floats, Rng::uniform(lo, hi).
How many values the range holds (0: all 2^64); panics when it is empty.
The value
ksteps past the start.
Functions
fillSource
pub fn fill(buf: SliceMut<u8>) Overwrite every byte of buf with random bytes. A List<u8>
passes as a view of all of it.
bytesSource
pub fn bytes(n: usize) -> List<u8> n random bytes.
secretSource
pub fn secret(n: usize) -> Secret n random bytes in secret storage (keys, seeds): no other copy.
rngSource
pub fn rng() -> Xoshiro256PlusPlus A generator seeded from the OS source (Xoshiro256PlusPlus::from_os).
For a stream that repeats, use Xoshiro256PlusPlus::seed(n).
f64Source
pub fn f64() -> f64 A value in [0, 1) from the shared generator. Python:
random.random().
use std::random;
let x = random::f64();
let n = random::range(1..=6);
assert(x >= 0.0 && x < 1.0 && n >= 1 && n <= 6);
rangeSource
pub fn range<R: SampleRange>(r: R) -> R::Item A value of r from the shared generator (see Rng::range).
normalSource
pub fn normal(mean: f64 = 0.0, std: f64 = 1.0) -> f64 A normal deviate from the shared generator. Python:
random.gauss(mean, std).
shuffleSource
pub fn shuffle<T>(xs: List<T>) xs in a random order, in place, from the shared generator.
choiceSource
pub fn choice<T>(xs: List<T>) -> T | none One item of xs from the shared generator, or none when it is
empty.