View source code
Display the source code in std/random.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Module std.random

Facilities for random number generation.

Disclaimer: The random number generators and API provided in this module are not designed to be cryptographically secure, and are therefore unsuitable for cryptographic or security-related purposes such as generating authentication tokens or network sequence numbers. For such needs, please use a reputable cryptographic library instead.

The new-style generator objects hold their own state so they are immune of threading issues. The generators feature a number of well-known and well-documented methods of generating random numbers. An overall fast and reliable means to generate random numbers is the Mt19937 generator, which derives its name from "Mersenne Twister with a period of 2 to the power of 19937". In memory-constrained situations, linear congruential generators such as MinstdRand0 and MinstdRand might be useful. The standard library provides an alias Random for whichever generator it considers the most fit for the target environment.

In addition to random number generators, this module features distributions, which skew a generator's output statistical distribution in various ways. So far the uniform distribution for integers and real numbers have been implemented.

Credits

The entire random number library architecture is derived from the excellent C++0X random number facility proposed by Jens Maurer and contributed to by researchers at the Fermi laboratory (excluding Xorshift).

Example

import std.algorithm.comparison : among, equal;
import std.range : iota;

// seed a random generator with a constant
auto rnd = Random(42);

// Generate a uniformly-distributed integer in the range [0, 14]
// If no random generator is passed, the global `rndGen` would be used
auto i = uniform(0, 15, rnd);
assert(i >= 0 && i < 15);

// Generate a uniformly-distributed real in the range [0, 100)
auto r = uniform(0.0L, 100.0L, rnd);
assert(r >= 0 && r < 100);

// Sample from a custom type
enum Fruit { apple, mango, pear }
auto f = rnd.uniform!Fruit;
with(Fruit)
assert(f.among(apple, mango, pear));

// Generate a 32-bit random number
auto u = uniform!uint(rnd);
static assert(is(typeof(u) == uint));

// Generate a random number in the range in the range [0, 1)
auto u2 = uniform01(rnd);
assert(u2 >= 0 && u2 < 1);

// Select an element randomly
auto el = 10.iota.choice(rnd);
assert(0 <= el && el < 10);

// Throw a dice with custom proportions
// 0: 20%, 1: 10%, 2: 60%
auto val = rnd.dice(0.2, 0.1, 0.6);
assert(0 <= val && val <= 2);

auto rnd2 = MinstdRand0(42);

// Select a random subsample from a range
assert(10.iota.randomSample(3, rnd2).equal([7, 8, 9]));

// Cover all elements in an array in random order
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert(10.iota.randomCover(rnd2).equal([7, 4, 2, 0, 1, 6, 8, 3, 9, 5]));

// Shuffle an array
version (X86_64) // https://issues.dlang.org/show_bug.cgi?id=15147
assert([0, 1, 2, 4, 5].randomShuffle(rnd2).equal([2, 0, 4, 5, 1]));

Functions

NameDescription
choice(range, urng) Returns a random, uniformly chosen, element e from the supplied Range range. If no random number generator is passed, the default rndGen is used.
dice() Rolls a dice with relative probabilities stored in proportions. Returns the index in proportions that was chosen.
partialShuffle(r, n, gen) Partially shuffles the elements of r such that upon returning r[0 .. n] is a random subset of r and is randomly ordered. r[n .. r.length] will contain the elements not in r[0 .. n]. These will be in an undefined order, but will not be random in the sense that their order after partialShuffle returns will not be independent of their order before partialShuffle was called.
randomCover(r, rng) Covers a given range r in a random manner, i.e. goes through each element of r once and only once, just in a random order. r must be a random-access range with length.
randomSample(r, n, total) Selects a random subsample out of r, containing exactly n elements. The order of elements is the same as in the original range. The total length of r must be known. If total is passed in, the total number of sample is considered to be total. Otherwise, RandomSample uses r.length.
randomShuffle(r, gen) Shuffles elements of r using gen as a shuffler. r must be a random-access range with length. If no RNG is specified, rndGen will be used.
rndGen() Global random number generator used by various functions in this module whenever no generator is specified. It is allocated per-thread and initialized to an unpredictable value for each thread.
uniform(a, b) Generates a number between a and b. The boundaries parameter controls the shape of the interval (open vs. closed on either side). Valid values for boundaries are "[]", "(]", "[)", and "()". The default interval is closed to the left and open to the right. The version that does not take urng uses the default generator rndGen.
uniform(urng) Generates a uniformly-distributed number in the range [T.min, T.max] for any integral or character type T. If no random number generator is passed, uses the default rndGen.
uniform01() Generates a uniformly-distributed floating point number of type T in the range [0, 1). If no random number generator is specified, the default RNG rndGen will be used as the source of randomness.
uniformDistribution(n, useThis) Generates a uniform probability distribution of size n, i.e., an array of size n of positive numbers of type F that sum to 1. If useThis is provided, it is used as storage.
unpredictableSeed() A "good" seed for initializing random number engines. Initializing with unpredictableSeed makes engines generate different random number sequences every run.

Structs

NameDescription
LinearCongruentialEngine Linear Congruential generator. When m = 0, no modulus is used.
MersenneTwisterEngine The Mersenne Twister generator.
RandomCover Covers a given range r in a random manner, i.e. goes through each element of r once and only once, just in a random order. r must be a random-access range with length.
RandomSample Selects a random subsample out of r, containing exactly n elements. The order of elements is the same as in the original range. The total length of r must be known. If total is passed in, the total number of sample is considered to be total. Otherwise, RandomSample uses r.length.
XorshiftEngine Xorshift generator. Implemented according to Xorshift RNGs (Marsaglia, 2003) when the size is small. For larger sizes the generator uses Sebastino Vigna's optimization of using an index to avoid needing to rotate the internal array.

Manifest constants

NameTypeDescription
isSeedable Test if Rng is seedable. The overload taking a SeedType also makes sure that the Rng can be seeded with SeedType.
isUniformRNG Test if Rng is a random-number generator. The overload taking a ElementType also makes sure that the Rng generates values of that type.

Aliases

NameTypeDescription
MinstdRand LinearCongruentialEngine!(uint,48271,0,2147483647) Define LinearCongruentialEngine generators with well-chosen parameters. MinstdRand0 implements Park and Miller's "minimal standard" generator that uses 16807 for the multiplier. MinstdRand implements a variant that has slightly better spectral behavior by using the multiplier 48271. Both generators are rather simplistic.
MinstdRand0 LinearCongruentialEngine!(uint,16807,0,2147483647) Define LinearCongruentialEngine generators with well-chosen parameters. MinstdRand0 implements Park and Miller's "minimal standard" generator that uses 16807 for the multiplier. MinstdRand implements a variant that has slightly better spectral behavior by using the multiplier 48271. Both generators are rather simplistic.
Mt19937 MersenneTwisterEngine!(uint,32L,624L,397L,31L,2567483615,11L,4294967295,7L,2636928640,15L,4022730752,18L,1812433253) A MersenneTwisterEngine instantiated with the parameters of the original engine MT19937, generating uniformly-distributed 32-bit numbers with a period of 2 to the power of 19937. Recommended for random number generation unless memory is severely restricted, in which case a LinearCongruentialEngine would be the generator of choice.
Mt19937_64 MersenneTwisterEngine!(ulong,64L,312L,156L,31L,-5403634167711393303L,29L,6148914691236517205L,17L,8202884508482404352L,37L,-2270628950310912L,43L,6364136223846793005L) A MersenneTwisterEngine instantiated with the parameters of the original engine MT19937-64, generating uniformly-distributed 64-bit numbers with a period of 2 to the power of 19937.
Random MersenneTwisterEngine!(uint,32L,624L,397L,31L,2567483615,11L,4294967295,7L,2636928640,15L,4022730752,18L,1812433253) The "default", "favorite", "suggested" random number generator type on the current platform. It is an alias for one of the previously-defined generators. You may want to use it if (1) you need to generate some nice random numbers, and (2) you don't care for the minutiae of the method being used.
unpredictableSeed unpredictableSeed A "good" seed for initializing random number engines. Initializing with unpredictableSeed makes engines generate different random number sequences every run.
Xorshift XorshiftEngine!(uint,128,11,-8,-19) Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". Xorshift is a Xorshift128's alias because 128bits implementation is mostly used.
Xorshift128 XorshiftEngine!(uint,128,11,-8,-19) Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". Xorshift is a Xorshift128's alias because 128bits implementation is mostly used.
Xorshift160 XorshiftEngine!(uint,160,2,-1,-4) Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". Xorshift is a Xorshift128's alias because 128bits implementation is mostly used.
Xorshift192 XorshiftEngine!(uint,192,-2,1,4) Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". Xorshift is a Xorshift128's alias because 128bits implementation is mostly used.
Xorshift32 XorshiftEngine!(uint,32,13,-17,15) Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". Xorshift is a Xorshift128's alias because 128bits implementation is mostly used.
Xorshift64 XorshiftEngine!(uint,64,10,-13,-10) Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". Xorshift is a Xorshift128's alias because 128bits implementation is mostly used.
Xorshift96 XorshiftEngine!(uint,96,10,-5,-26) Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "Xorshift RNGs". Xorshift is a Xorshift128's alias because 128bits implementation is mostly used.
XorshiftEngine XorshiftEngine!(UIntType,bits,a,-b,c) Xorshift generator. Implemented according to Xorshift RNGs (Marsaglia, 2003) when the size is small. For larger sizes the generator uses Sebastino Vigna's optimization of using an index to avoid needing to rotate the internal array.

Authors

Andrei Alexandrescu Masahiro Nakagawa (Xorshift random generator) Joseph Rushton Wakeling (Algorithm D for random sampling) Ilya Yaroshenko (Mersenne Twister implementation, adapted from mir-random)

License

Boost License 1.0.