Standard Library: Random
The std::core::random module provides high-quality random number generation
using a ChaCha8 PRNG. All functions use thread-local state for performance
and safety.
Importing
Section titled “Importing”from std::core::random use { random, random_int, random_seed, random_normal, random_array }Functions
Section titled “Functions”random
Section titled “random”Generate a random floating-point number in [0, 1).
let r = random() // e.g. 0.734521...random_int
Section titled “random_int”Generate a random integer in [lo, hi] (inclusive on both ends).
let dice = random_int(1, 6) // 1, 2, 3, 4, 5, or 6let coin = random_int(0, 1) // 0 or 1random_seed
Section titled “random_seed”Seed the RNG for reproducible sequences. Calling random_seed with the same
value resets the generator to the same state, so subsequent calls to random
produce identical results.
random_seed(42)let r1 = random()
random_seed(42)let r2 = random()// r1 == r2random_normal
Section titled “random_normal”Generate a random number from a normal (Gaussian) distribution with the given mean and standard deviation. The standard deviation must be non-negative.
let shock = random_normal(0.0, 0.02) // mean=0, std=2%let height = random_normal(170.0, 10.0) // mean=170cm, std=10cmrandom_array
Section titled “random_array”Generate an array of n random numbers in [0, 1).
let samples = random_array(1000)print(samples.length) // 1000Function Reference
Section titled “Function Reference”| Function | Signature | Description |
|---|---|---|
random() | () -> number | Random float in [0, 1) |
random_int(lo, hi) | (int, int) -> int | Random integer in [lo, hi] |
random_seed(seed) | (int) -> () | Seed the PRNG for reproducibility |
random_normal(mean, std) | (number, number) -> number | Random number from N(mean, std) |
random_array(n) | (int) -> Vec<number> | Array of n random floats |
See Also
Section titled “See Also”- Standard Library: Math — statistical functions (
mean,std,variance)