MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
Rand

Overview

A small, fast, seeded pseudo-random generator.

The generator is splitmix64, so the same seed gives the same sequence on every platform, unlike rand(). Use it for tests, simulations and shuffles, where a failure must be reproducible from its seed.

  • A zero-initialised Rand is valid. Set state to pick a seed.
  • Each Rand is independent and holds no global state. Copy one to fork its sequence.
  • rand_below() is unbiased. It rejects the few values that would make some results more likely than others, instead of a plain % n.
Rand dice = { .state = 2026 };
uint64_t roll = 1 + rand_below(&dice, 6); /* 1 to 6 */
Warning
Not for secrets. The sequence is predictable from one output. Use the operating system's generator for keys and tokens.

Data Structures

struct  Rand
 Generator state. More...

Functions

uint64_t rand_next (Rand *r)
 The next 64 random bits.
uint64_t rand_below (Rand *r, uint64_t n)
 A uniform value in [0, n).

Data Structure Documentation

◆ Rand

struct Rand

Generator state.

Copy it to fork a sequence.

Definition at line 26 of file rand.h.

Data Fields
uint64_t state The seed, advanced by every call.

Function Documentation

◆ rand_next()

uint64_t rand_next ( Rand * r)

The next 64 random bits.

Definition at line 5 of file rand.c.

◆ rand_below()

uint64_t rand_below ( Rand * r,
uint64_t n )

A uniform value in [0, n).

Precondition
n is not 0. An assert checks it.

Definition at line 12 of file rand.c.