Skip to main content

Random Module

The random module provides pseudorandom number generation for Mux programs. It uses a time-based seed by default, but can be manually seeded for reproducible results.

Import

Mux
Loading...

Functions

random.seed

random.seed(int seed) returns void

Initialize the random number generator with a specific seed. Use this when you need reproducible random sequences, such as in testing or simulations.

seed_example.mux
Loading...

random.next_int

random.next_int() returns int

Generate a random integer between 0 and RAND_MAX (platform-dependent, typically 2,147,483,647).

The generator auto-initializes with the current time on first use if not explicitly seeded.

dice_roll.mux
Loading...

random.next_range

random.next_range(int min, int max) returns int

Generate a random integer in the range [min, max). The lower bound is inclusive, the upper bound is exclusive.

Returns min if min >= max.

lottery_numbers.mux
Loading...

random.next_float

random.next_float() returns float

Generate a random floating-point number in the range [0.0, 1.0).

Useful for probabilities, animations, and scientific calculations.

probability_example.mux
Loading...

random.next_bool

random.next_bool() returns bool

Generate a random boolean value (true or false) with equal probability (50/50).

coin_flip.mux
Loading...

Complete Example

random_demo.mux
Loading...

Implementation Details

The random module uses a custom Linear Congruential Generator (LCG) with the following characteristics:

  • Thread safety: Uses a Mutex-protected state with Once-based initialization
  • Auto-initialization: Seeds automatically with current time if not explicitly seeded
  • Range distribution: next_range scales the generator's output by the span with a fixed-point multiply rather than taking a remainder. Like any method without a rejection step this leaves a slight bias, growing with the size of the range relative to the generator's 31-bit output
  • Float precision: Produces values with approximately 31 bits of precision

For cryptographic applications or high-precision simulations, consider using a specialized library.