Skip to content

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.

from std::core::random use { random, random_int, random_seed, random_normal, random_array }

Generate a random floating-point number in [0, 1).

let r = random() // e.g. 0.734521...

Generate a random integer in [lo, hi] (inclusive on both ends).

let dice = random_int(1, 6) // 1, 2, 3, 4, 5, or 6
let coin = random_int(0, 1) // 0 or 1

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 == r2

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=10cm

Generate an array of n random numbers in [0, 1).

let samples = random_array(1000)
print(samples.length) // 1000
FunctionSignatureDescription
random()() -> numberRandom float in [0, 1)
random_int(lo, hi)(int, int) -> intRandom integer in [lo, hi]
random_seed(seed)(int) -> ()Seed the PRNG for reproducibility
random_normal(mean, std)(number, number) -> numberRandom number from N(mean, std)
random_array(n)(int) -> Vec<number>Array of n random floats