Base Random Library¶
The random library provides a set of high-quality primitives for stochastic processes and data manipulation. Unlike basic modulo-based generators, this library utilizes unbiased sampling techniques such as Lemire’s algorithm for integers and Fisher-Yates for permutations—to ensure a truly uniform distribution across all ranges. These tools are essential for everything from simple game logic and randomized testing to data science applications like bootstrapping and shuffling datasets.
Numerical Randomness¶
rand-int¶
- (rand-int [limit])
Returns a uniformly distributed random integer in the range [0, limit). If limit is omitted, it defaults to the maximum value of a 32-bit unsigned integer (4,294,967,295).
- Parameters:
limit (integer) – The upper bound (exclusive).
- Returns:
A random integer.
- Return type:
integer
Example
--> (rand-int 10) 7
rand-dbl¶
- (rand-dbl)
Returns a uniformly distributed random real number in the range [0.0, 1.0). The result maintains 53 bits of precision, consistent with IEEE 754 double-precision floats.
- Returns:
A random real number.
- Return type:
real
rand-uniform¶
- (rand-uniform min max)
Returns a uniformly distributed random real number in the range [min, max).
- Parameters:
min (integer, rational, or real) – The lower bound (inclusive).
max (integer, rational, or real) – The upper bound (exclusive).
- Returns:
A random real number.
- Return type:
real
Sequence Manipulation¶
shuffle¶
- (shuffle seq)
Returns a new sequence containing the elements of seq in a randomized order. This uses an unbiased Fisher-Yates permutation. The original sequence remains unmodified.
- Parameters:
seq (list or vector) – The sequence to shuffle.
- Returns:
A shuffled version of the input.
- Return type:
list or vector (matches input type)
Example
--> (shuffle '(1 2 3 4 5)) (3 5 1 4 2)
rand-choice¶
- (rand-choice seq)
Returns a single element chosen uniformly at random from seq.
- Parameters:
seq (list or vector) – The sequence to choose from.
- Returns:
A single element from the sequence.
- Return type:
any
rand-choices¶
- (rand-choices seq k)
Returns a new sequence containing k elements chosen uniformly at random from seq with replacement (meaning the same element can be picked multiple times).
- Parameters:
seq (list or vector) – The sequence to sample from.
k (integer) – The number of elements to return.
- Returns:
A new sequence of length k.
- Return type:
list or vector (matches input type)
Example
--> (rand-choices #(heads tails) 3) #(tails heads tails)