Random Numbers & Distributions in D — mir-random Guide
Generate reproducible random numbers and sample from statistical distributions (uniform, normal, exponential, gamma) in D with mir-random. Compiled against current Mir source.
How to generate random numbers and sample distributions with mir-random. For the full API, browse mir-random.libmir.org.
All examples compile against current
mir-random. mir-random separates engines (the bit source) from variables (distributions that consume an engine) — pick an engine, then draw from any distribution with it. Note: mir-random's PRNGs are statistically sound but not cryptographically secure.
Reproducible engine + uniform draws
import mir.random;
import mir.random.variable;
import mir.random.engine.xorshift;
auto gen = Xorshift(1234); // explicit seed → reproducible
auto u = uniformVar!double(0, 1)(gen); // uniform in [0, 1)
auto i = uniformVar!int(0, 6)(gen); // integer in [0, 6]Seed an engine explicitly when you need reproducible streams (tests, simulations). uniformVar!T(lo, hi) builds a distribution object; calling it with an engine draws a value.
Choosing an engine
import mir.random.variable;
import mir.random.engine.xorshift;
import mir.random.engine.mersenne_twister;
auto fast = Xorshift(1234); // small, fast, good general-purpose
auto mt = Mt19937_64(42); // Mersenne Twister, long period
auto v = uniformVar!double(-5, 5)(mt);Xorshift is a compact, fast default; Mt19937_64 gives the familiar Mersenne Twister with a very long period. mir-random also ships PCG and xoshiro engines — see mir.random.engine.
Sampling distributions
import mir.random.variable;
import mir.random.engine.xorshift;
auto gen = Xorshift(1234);
auto n = normalVar!double(0, 1)(gen); // standard normal (mean 0, sd 1)
auto e = exponentialVar!double(1.5)(gen); // exponential
auto g = gammaVar!double(2.0)(gen); // gamma, shape = 2Each *Var constructor returns a reusable distribution object — build it once, draw many times by calling it with an engine. The full catalogue (Bernoulli, Binomial, Beta, Cauchy, Poisson, …) is in mir.random.variable.
Where to go next
- mir.random.variable — every distribution
- mir.random.engine — every PRNG engine
- mir.random.ndvariable — multivariate sampling
- ndslice Cookbook — fill arrays and process the results
ndslice Cookbook — Common Recipes for D Multidimensional Arrays
A practical, task-oriented cookbook for mir-algorithm's ndslice — create, reshape, slice, map, reduce, and fuse multidimensional arrays in D. Every example is compiled against current Mir source.
Serialization in D — JSON, MessagePack, CBOR & ION with mir-ion
Serialize and deserialize D structs to JSON, MessagePack, and Amazon ION with mir-ion — one set of attributes, many formats. Compiled against current Mir source.