libstd/random

A seedable xorshift64* generator (RandomState) with uniform integers in a range, floats in [0, 1), booleans, and true entropy from the operating system (getrandom on Linux, BCryptGenRandom on Windows).

#include <libstd/random>

Includes libstd/type. Same functions and constant names on Linux and Windows: the system-specific part is in wrapper/linux/sysrandom and wrapper/windows/sysrandom (see Linux and Windows). Links the shared library bcrypt.dll (FFI).

Example

#include <libstd/stdio>
#include <libstd/random>

rng = random_new()                       // seeded from the kernel
d = random_int(rng, 1, 6)                // 1..6 inclusive
f = random_float(rng)                    // [0.0, 1.0)

fixed = new RandomState()
random_seed(fixed, 12345 as long)        // reproducible sequence
print(random_next(fixed), "\n")

Classes

class
RandomState

The 64-bit generator state; seed it with random_seed or create it seeded with random_new.

    state long

Functions

def getrandom_bytes(buf: str, n: int) -> int

Fills buf with n bytes of kernel entropy, retrying until done.

def random_seed_from_os() -> long

8 bytes of kernel entropy as a long: the right seed for random_seed.

def random_seed(rng: RandomState, seed: long) -> None

(Re)initialises the generator. Equal seeds give equal sequences; a zero seed is replaced so the generator never sticks at 0.

def random_new() -> RandomState

A new RandomState seeded from the kernel.

def random_next(rng: RandomState) -> long

The next 64-bit value of the xorshift64* sequence.

def random_long(rng: RandomState, min: long, max: long) -> long

A uniform long in the inclusive range [min, max] (rejection sampling, no modulo bias).

def random_int(rng: RandomState, min: int, max: int) -> int

A uniform int in [min, max].

def random_float(rng: RandomState) -> float

A uniform float in [0.0, 1.0) from the top 53 bits.

def random_bool(rng: RandomState) -> int

0 or 1.

def sys_getrandom(buf: str, buflen: int, flags: int) -> int

Raw entropy: the getrandom(2) system call on Linux (it may return fewer bytes than requested), BCryptGenRandom on Windows (it fills the whole buffer). Returns the bytes written, or a negative error.