Rand Module
The rand module provides random number generation, random selection, and
shuffling. Import it with the rand. prefix.
Random Floats
rand.random()
Returns a random float in the half-open interval [0.0, 1.0).
rand.random() // e.g. 0.6645600532184904rand.uniform(a, b)
Returns a random float in the closed interval [a, b].
rand.uniform(1.0, 10.0) // e.g. 7.234
rand.uniform(-1, 1) // e.g. -0.412Random Integers
rand.int()
Returns a random non-negative integer. Optionally accepts one or two arguments to constrain the range.
rand.int() // random non-negative integer
rand.int(10) // random integer in [0, 10)
rand.int(5, 15) // random integer in [5, 15)rand.randint(a, b)
Returns a random integer in the closed interval [a, b], inclusive of both endpoints.
rand.randint(1, 6) // simulates a die roll: 1, 2, 3, 4, 5, or 6
rand.randint(0, 100) // random integer from 0 to 100 inclusiveDistributions
rand.normal()
Returns a random value from a normal (Gaussian) distribution. Defaults to
mean 0 and standard deviation 1. Optionally accepts mu and sigma parameters.
rand.normal() // standard normal: mean=0, stddev=1
rand.normal(100, 15) // mean=100, stddev=15rand.exponential()
Returns a random value from an exponential distribution. Defaults to lambda = 1. Optionally accepts a lambda parameter.
rand.exponential() // lambda=1
rand.exponential(0.5) // lambda=0.5Selection and Sampling
rand.choice(list)
Returns a single random element from a list.
let colors = ["red", "green", "blue"]
rand.choice(colors) // e.g. "green"rand.sample(list, k)
Returns a list of k unique random elements from the given list. The
original list is not modified.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
rand.sample(numbers, 3) // e.g. [7, 2, 10]rand.shuffle(list)
Shuffles a list in place, randomizing the order of its elements.
let deck = [1, 2, 3, 4, 5]
rand.shuffle(deck)
// deck is now in a random order, e.g. [3, 1, 5, 2, 4]Random Bytes
rand.bytes(n)
Returns a list of n random integers in the range 0--255. Useful for
generating tokens, nonces, or random identifiers.
rand.bytes(4) // e.g. [182, 47, 233, 91]