www.digitalmars.com

D Programming Language 2.0

Last update Tue Nov 27 20:24:56 2007

std.random

Facilities for random number generation. The old-style functions rand_seed and rand will soon be deprecated as they rely on global state and as such are subjected to various thread-related issues.

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 finds the most fit for the target environment.

Example:
Random gen;
// Generate a uniformly-distributed integer in the range [0, 15]
auto i = uniform!(int)(gen, 0, 15);
// Generate a uniformly-distributed real in the range [0, 100)
auto r = uniform!(real)(gen, 0.0L, 100.0L);
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.

Author:
Andrei Alexandrescu

Credits:
The entire random number library architecture is derived from the excellent C++0X random number facility proposed by Jens Maurer and contrinuted to by researchers at the Fermi laboratory.

struct LinearCongruentialEngine(UIntType,UIntType a,UIntType c,UIntType m);
Linear Congruential generator.

alias ResultType;
Alias for the generated type UIntType.

bool hasFixedRange;
Does this generator have a fixed range? (true).

ResultType min;
Lowest generated value.

ResultType max;
Highest generated value.

UIntType multiplier;
The parameters of this distribution. The random number is x = (x * a + c) % m.

UIntType increment;
The parameters of this distribution. The random number is x = (x * a + c) % m.

UIntType modulus;
The parameters of this distribution. The random number is x = (x * a + c) % m.

LinearCongruentialEngine opCall(UIntType x0 = 1);
Constructs a LinearCongruentialEngine generator.

void seed(UIntType x0 = 1);
(Re)seeds the generator.

UIntType next();
Returns the next number in the random sequence.

void discard(ulong n);
Discards next n samples.

bool opEquals(LinearCongruentialEngine rhs);
Compares against rhs for equality.

alias MinstdRand0;
alias MinstdRand;
Define LinearCongruentialEngine generators with "good" parameters.

Example:
   // seed with a constant
   auto rnd0 = MinstdRand0(1);
   auto n = rnd0.next; // same for each run
   // Seed with an unpredictable value
   rnd0.seed(unpredictableSeed);
   n = rnd0.next; // different across runs


struct MersenneTwisterEngine(UIntType,uint w,uint n,uint m,uint r,UIntType a,uint u,uint s,UIntType b,uint t,UIntType c,uint l);
The Mersenne Twister generator.

alias ResultType;
Result type (an alias for UIntType).

size_t wordSize;
Parameter for the generator.

size_t stateSize;
Parameter for the generator.

size_t shiftSize;
Parameter for the generator.

size_t maskBits;
Parameter for the generator.

UIntType xorMask;
Parameter for the generator.

UIntType temperingU;
Parameter for the generator.

size_t temperingS;
Parameter for the generator.

UIntType temperingB;
Parameter for the generator.

size_t temperingT;
Parameter for the generator.

UIntType temperingC;
Parameter for the generator.

size_t temperingL;
Parameter for the generator.

UIntType min;
Smallest generated value (0).

UIntType max;
Largest generated value.

UIntType defaultSeed;
The default seed value.

MersenneTwisterEngine opCall(ResultType value);
Constructs a MersenneTwisterEngine object

void seed(ResultType value = defaultSeed);
Constructs a MersenneTwisterEngine object

uint next();
Returns the next random value.

void discard(ulong n);
Discards next n samples.

alias Mt19937;
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.

Example:
   // seed with a constant
   Mt19937 gen;
   auto n = gen.next; // same for each run
   // Seed with an unpredictable value
   gen.seed(unpredictableSeed);
   n = gen.next; // different across runs


typedef Random;
The "default", "favorite", "suggested" random number generator on the current platform. It is a typedef 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.

ulong unpredictableSeed();
A "good" seed for initializing random number engines. Initializing with unpredictableSeed makes engines generate different random number sequences every run.

Example:
auto rnd = Random(unpredictableSeed);
auto n = rnd.next;
...


struct UniformDistribution(NumberType,char leftLim = '[',char rightLim = ')'
;
Generates uniformly-distributed numbers within a range using an external generator. The leftLim and rightLim parameters control the shape of the interval (open vs. closed on either side). The default interval is [a, b).

Example:
auto a = new double[20];
Random gen;
auto rndIndex = UniformDistribution!(uint)(0, a.length);
auto rndValue = UniformDistribution!(double)(0, 1);
// Get a random index into the array
auto i = rndIndex.next(gen);
// Get a random probability, i.e., a real number in [0, 1)
auto p = rndValue.next(gen);
// Assign that value to that array element
a[i] = p;
auto digits = UniformDistribution!(char, '[', ']')('0', '9');
auto percentages = UniformDistribution!(double, '(', ']')(0.0, 100.0);
// Get a digit in ['0', '9']
auto digit = digits.next(gen);
// Get a number in (0.0, 100.0]
auto p = percentages.next(gen);


UniformDistribution opCall(NumberType a, NumberType b);
Constructs a UniformDistribution able to generate numbers in the interval [min, max

if closedRight is false.
ResultType a();
Returns the smallest random value generated.

ResultType b();
Returns the largest random value generated.

void reset();
Does nothing (provided for conformity with other distributions).

template next(UniformRandomNumberGenerator)
Returns a random number using UniformRandomNumberGenerator as back-end.

ResultType next(ref UniformRandomNumberGenerator urng);
Returns a random number using UniformRandomNumberGenerator as back-end.

)
template uniform(T,char leftLim = '[',char rightLim = ')'
)
Convenience function that generates a number in an interval by forwarding to UniformDistribution!(T, leftLim, rightLim)(a, b).next.

Example:
Random gen(unpredictableSeed);
// Generate an integer in [0, 1024]
auto a = uniform!(int)(gen, 0, 1024);
// Generate a float in [0, 1)
auto a = uniform!(float)(gen, 0.0f, 1.0f);


void randomShuffle(T,SomeRandomGen)(T[] array, ref SomeRandomGen r);
Shuffles elements of array using r as a shuffler.

void rand_seed(uint seed, uint index);
The random number generator is seeded at program startup with a random value. This ensures that each program generates a different sequence of random numbers. To generate a repeatable sequence, use rand_seed() to start the sequence. seed and index start it, and each successive value increments index. This means that the nth random number of the sequence can be directly generated by passing index + n to rand_seed().

Note:
This is more random, but slower, than C's rand() function. To use C's rand() instead, import std.c.stdlib.

BUGS:
Shares a global single state, not multithreaded. SCHEDULED FOR DEPRECATION.

uint rand();
Get the next random number in sequence.

BUGS:
Shares a global single state, not multithreaded. SCHEDULED FOR DEPRECATION.

)