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
			a local clone.
		
	std.random
Facilities for 
random number generation.
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.
Example:
// Generate a uniformly-distributed integer in the range [0, 14] auto i = uniform(0, 15); // Generate a uniformly-distributed real in the range [0, 100) // using a specific random generator Random gen; auto r = uniform(0.0L, 100.0L, gen); // Generate a 32-bit random number auto l = uniform!uint();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.
Source: std/random.d
License: 
Authors: 
Andrei Alexandrescu
           Masahiro Nakagawa (Xorshift 
random generator)
           Joseph Rushton Wakeling (Algorithm D for random sampling)
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).
- enum boolisUniformRNG(Rng, ElementType);
 enum boolisUniformRNG(Rng);
- Test if Rng is a random-number generator. The overload taking a ElementType also makes sure that the Rng generates values of that type.A random-number generator has at least the following features:- it's an InputRange
- it has a 'bool isUniformRandom' field readable in CTFE
 
- enum boolisSeedable(Rng, SeedType);
 enum boolisSeedable(Rng);
- Test if Rng is seedable. The overload taking a SeedType also makes sure that the Rng can be seeded with SeedType.A seedable random-number generator has the following additional features:- it has a 'seed(ElementType)' function
 
- structLinearCongruentialEngine(UIntType, UIntType a, UIntType c, UIntType m) if (isUnsigned!UIntType);
- Linear Congruential generator.- enum boolisUniformRandom;
- Mark this as a Rng
- enum boolhasFixedRange;
- Does this generator have a fixed range? (true).
- enum UIntTypemin;
- Lowest generated value (1 if c == 0, 0 otherwise).
- enum UIntTypemax;
- Highest generated value (modulus - 1).
- enum UIntTypemultiplier;
 enum UIntTypeincrement;
 enum UIntTypemodulus;
- The parameters of this distribution. The random number is x = (x * multipler +increment) %modulus.
- pure @safe this(UIntTypex0);
- Constructs a LinearCongruentialEngine generator seeded withx0.
- pure @safe voidseed(UIntTypex0= 1);
- (Re)seeds the generator.
- pure nothrow @nogc @safe voidpopFront();
- Advances the random sequence.
- const pure nothrow @nogc @property @safe UIntTypefront();
- Returns the current number in the random sequence.
- pure nothrow @nogc @property @safe typeof(this)save();
- enum boolempty;
- Alwaysfalse(random generators are infinite ranges).
- const pure nothrow @nogc @safe boolopEquals(ref const LinearCongruentialEnginerhs);
- Compares againstrhsfor equality.
 
- aliasMinstdRand0= LinearCongruentialEngine!(uint, 16807u, 0u, 2147483647u).LinearCongruentialEngine;
 aliasMinstdRand= LinearCongruentialEngine!(uint, 48271u, 0u, 2147483647u).LinearCongruentialEngine;
- Define LinearCongruentialEngine generators with well-chosen parameters.MinstdRand0implements Park and Miller's "minimal standard" generator that uses 16807 for the multiplier.MinstdRandimplements a variant that has slightly better spectral behavior by using the multiplier 48271. Both generators are rather simplistic.Examples:// seed with a constant auto rnd0 = MinstdRand0(1); auto n = rnd0.front; // same for each run // Seed with an unpredictable value rnd0.seed(unpredictableSeed); n = rnd0.front; // different across runs 
- structMersenneTwisterEngine(UIntType, size_t w, size_t n, size_t m, size_t r, UIntType a, size_t u, size_t s, UIntType b, size_t t, UIntType c, size_t l) if (isUnsigned!UIntType);
- The Mersenne Twister generator.- enum boolisUniformRandom;
- Mark this as a Rng
- enum size_twordSize;
 enum size_tstateSize;
 enum size_tshiftSize;
 enum size_tmaskBits;
 enum UIntTypexorMask;
 enum UIntTypetemperingU;
 enum size_ttemperingS;
 enum UIntTypetemperingB;
 enum size_ttemperingT;
 enum UIntTypetemperingC;
 enum size_ttemperingL;
- Parameters for the generator.
- enum UIntTypemin;
- Smallest generated value (0).
- enum UIntTypemax;
- Largest generated value.
- enum UIntTypedefaultSeed;
- The default seed value.
- pure nothrow @nogc @safe this(UIntTypevalue);
- Constructs a MersenneTwisterEngine object.
- pure nothrow @nogc @safe voidseed()(UIntTypevalue= defaultSeed);
- Seeds a MersenneTwisterEngine object.Note: This seedfunction gives 2^32 starting points. To allow the RNG to be started in any one of its internal states use theseedoverload taking an InputRange.
- voidseed(T)(Trange)
 if (isInputRange!T && is(Unqual!(ElementType!T) == UIntType));
- Seeds a MersenneTwisterEngine object using an InputRange.Throws:Exception if the InputRange didn't provide enough elements toseedthe generator. The number of elements required is the 'n' template parameter of the MersenneTwisterEngine struct.Examples:import std.algorithm.iteration : map; import std.range : repeat; Mt19937 gen; gen.seed(map!((a) => unpredictableSeed)(repeat(0))); 
- pure nothrow @nogc @safe voidpopFront();
- Advances the generator.
- pure nothrow @nogc @property @safe UIntTypefront();
- Returns the current random value.
- pure nothrow @nogc @property @safe typeof(this)save();
- enum boolempty;
- Alwaysfalse.
 
- aliasMt19937= MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 7LU, 2636928640u, 15LU, 4022730752u, 18LU).MersenneTwisterEngine;
- 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.Examples:// seed with a constant Mt19937 gen; auto n = gen.front; // same for each run // Seed with an unpredictable value gen.seed(unpredictableSeed); n = gen.front; // different across runs 
- structXorshiftEngine(UIntType, UIntType bits, UIntType a, UIntType b, UIntType c) if (isUnsigned!UIntType);
- Xorshift generator using 32bit algorithm.Implemented according to Xorshift RNGs.bits period 32 2^32 - 1 64 2^64 - 1 96 2^96 - 1 128 2^128 - 1 160 2^160 - 1 192 2^192 - 2^32 - enum boolisUniformRandom;
- Mark this as a Rng
- enum autoempty;
- Alwaysfalse(random generators are infinite ranges).
- enum UIntTypemin;
- Smallest generated value.
- enum UIntTypemax;
- Largest generated value.
- pure nothrow @nogc @safe this(UIntTypex0);
- Constructs a XorshiftEngine generator seeded withx0.
- pure nothrow @nogc @safe voidseed(UIntTypex0);
- (Re)seeds the generator.
- const pure nothrow @nogc @property @safe UIntTypefront();
- Returns the current number in the random sequence.
- pure nothrow @nogc @safe voidpopFront();
- Advances the random sequence.
- pure nothrow @nogc @property @safe typeof(this)save();
- Captures a range state.
- const pure nothrow @nogc @safe boolopEquals(ref const XorshiftEnginerhs);
- Compares againstrhsfor equality.
 
- aliasXorshift32= XorshiftEngine!(uint, 32u, 13u, 17u, 15u).XorshiftEngine;
 aliasXorshift64= XorshiftEngine!(uint, 64u, 10u, 13u, 10u).XorshiftEngine;
 aliasXorshift96= XorshiftEngine!(uint, 96u, 10u, 5u, 26u).XorshiftEngine;
 aliasXorshift128= XorshiftEngine!(uint, 128u, 11u, 8u, 19u).XorshiftEngine;
 aliasXorshift160= XorshiftEngine!(uint, 160u, 2u, 1u, 4u).XorshiftEngine;
 aliasXorshift192= XorshiftEngine!(uint, 192u, 2u, 1u, 4u).XorshiftEngine;
 aliasXorshift= XorshiftEngine!(uint, 128u, 11u, 8u, 19u).XorshiftEngine;
- Define XorshiftEngine generators with well-chosen parameters. See each bits examples of "XorshiftRNGs".Xorshiftis aXorshift128's alias because 128bits implementation is mostly used.Examples:// Seed with a constant auto rnd = Xorshift(1); auto num = rnd.front; // same for each run // Seed with an unpredictable value rnd.seed(unpredictableSeed); num = rnd.front; // different across rnd 
- @property @trusted uintunpredictableSeed();
- A "good" seed for initializing random number engines. Initializing withunpredictableSeedmakes engines generate different random number sequences every run.Returns:A single unsigned integer seed value, different on each successive callExamples:auto rnd = Random(unpredictableSeed); auto n = rnd.front; static assert(is(typeof(n) == uint)); 
- aliasRandom= MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 2567483615u, 11LU, 7LU, 2636928640u, 15LU, 4022730752u, 18LU).MersenneTwisterEngine;
- 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.
- @property ref @safe RandomrndGen();
- 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.Returns:A singleton instance of the default random number generator
- autouniform(string boundaries = "[)", T1, T2)(T1a, T2b)
 if (!is(CommonType!(T1, T2) == void));
 autouniform(string boundaries = "[)", T1, T2, UniformRandomNumberGenerator)(T1a, T2b, ref UniformRandomNumberGeneratorurng)
 if (isFloatingPoint!(CommonType!(T1, T2)) && isUniformRNG!UniformRandomNumberGenerator);
- Generatesanumber betweenaandb. 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 takeurnguses the default generator rndGen.Parameters:T1 alower bound of the uniform distribution T2 bupper bound of the uniform distribution UniformRandomNumberGenerator urng(optional) random number generator to use; if not specified, defaults to rndGen Returns:A single random variate drawn from the uniform distribution betweenaandb, whose type is the common type of these parametersExamples:auto gen = Random(unpredictableSeed); // Generate an integer in [0, 1023] auto a = uniform(0, 1024, gen); // Generate a float in [0, 1) auto b = uniform(0.0f, 1.0f, gen); 
- autouniform(T, UniformRandomNumberGenerator)(ref UniformRandomNumberGeneratorurng)
 if (!is(T == enum) && (isIntegral!T || isSomeChar!T) && isUniformRNG!UniformRandomNumberGenerator);
 autouniform(T)()
 if (!is(T == enum) && (isIntegral!T || isSomeChar!T));
- 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.Parameters:UniformRandomNumberGenerator urng(optional) random number generator to use; if not specified, defaults to rndGen Returns:Random variate drawn from the uniform distribution across all possible values of the integral or character type T.
- autouniform(E, UniformRandomNumberGenerator)(ref UniformRandomNumberGeneratorurng)
 if (is(E == enum) && isUniformRNG!UniformRandomNumberGenerator);
 autouniform(E)()
 if (is(E == enum));
- Returns a uniformly selected member of enum E. If no random number generator is passed, uses the default rndGen.Parameters:UniformRandomNumberGenerator urng(optional) random number generator to use; if not specified, defaults to rndGen Returns:Random variate drawn with equal probability from any of the possible values of the enum E.Examples:enum Fruit { apple, mango, pear } auto randFruit = uniform!Fruit(); 
- Tuniform01(T = double)()
 if (isFloatingPoint!T);
 Tuniform01(T = double, UniformRNG)(ref UniformRNGrng)
 if (isFloatingPoint!T && isUniformRNG!UniformRNG);
- 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.uniform01offers a faster generation of random variates than the equivalent uniform!"[)"(0.0, 1.0) and so may be preferred for some applications.Parameters:UniformRNG rng(optional) random number generator to use; if not specified, defaults to rndGen Returns:Floating-point random variate of type T drawn from the uniform distribution across the half-open interval [0, 1).
- F[]uniformDistribution(F = double)(size_tn, F[]useThis= null)
 if (isFloatingPoint!F);
- Generates a uniform probability distribution of sizen, i.e., an array of sizenof positive numbers of type F that sum to 1. IfuseThisis provided, it is used as storage.
- ref autochoice(Range, RandomGen = Random)(auto ref Rangerange, ref RandomGenurng= rndGen)
 if (isRandomAccessRange!Range && hasLength!Range && isUniformRNG!RandomGen);
- Returns a random, uniformly chosen, element e from the supplied Rangerange. If no random number generator is passed, the default rndGen is used.Parameters:Range rangea random access rangethat has the length property definedRandomGen urng(optional) random number generator to use; if not specified, defaults to rndGen Returns:A single random element drawn from therange. If it can, it will return a ref to therangeelement, otherwise it will return a copy.Examples:import std.algorithm.searching : canFind; auto array = [1, 2, 3, 4, 5]; auto elem = choice(array); assert(canFind(array, elem), "Choice did not return a valid element from the given Range"); auto urng = Random(unpredictableSeed); elem = choice(array, urng); assert(canFind(array, elem), "Choice did not return a valid element from the given Range"); 
- voidrandomShuffle(Range, RandomGen)(Ranger, ref RandomGengen)
 if (isRandomAccessRange!Range && isUniformRNG!RandomGen);
 voidrandomShuffle(Range)(Ranger)
 if (isRandomAccessRange!Range);
- Shuffles elements ofrusinggenas a shuffler.rmust be a random-access range with length. If no RNG is specified, rndGen will be used.Parameters:Range rrandom-access range whose elements are to be shuffled RandomGen gen(optional) random number generator to use; if not specified, defaults to rndGen 
- voidpartialShuffle(Range, RandomGen)(Ranger, in size_tn, ref RandomGengen)
 if (isRandomAccessRange!Range && isUniformRNG!RandomGen);
 voidpartialShuffle(Range)(Ranger, in size_tn)
 if (isRandomAccessRange!Range);
- Partially shuffles the elements ofrsuch that upon returningr[0..n] is a random subset ofrand is randomly ordered.r[n..r.length] will contain the elements not inr[0..n]. These will be in an undefined order, but will not be random in the sense that their order afterpartialShufflereturns will not be independent of their order beforepartialShufflewas called.rmust be a random-access range with length.nmust be less than or equal tor.length. If no RNG is specified, rndGen will be used.Parameters:Range rrandom-access range whose elements are to be shuffled size_t nnumber of elements of rto shuffle (counting from the beginning); must be less thanr.lengthRandomGen gen(optional) random number generator to use; if not specified, defaults to rndGen 
- size_tdice(Rng, Num)(ref Rngrnd, Num[]proportions...)
 if (isNumeric!Num && isForwardRange!Rng);
 size_tdice(R, Range)(ref Rrnd, Rangeproportions)
 if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);
 size_tdice(Range)(Rangeproportions)
 if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);
 size_tdice(Num)(Num[]proportions...)
 if (isNumeric!Num);
- Rolls adicewith relative probabilities stored inproportions. Returns the index inproportionsthat was chosen.Parameters:Rng rnd(optional) random number generator to use; if not specified, defaults to rndGen Num[] proportionsforward range or list of individual values whose elements correspond to the probabilities with which to choose the corresponding index value Returns:Random variate drawn from the index values [0, ...proportions.length - 1], with the probability of getting an individual index value i being proportional toproportions[i].Examples:auto x = dice(0.5, 0.5); // x is 0 or 1 in equal proportions auto y = dice(50, 50); // y is 0 or 1 in equal proportions auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time, // and 2 10% of the time 
- structRandomCover(Range, UniformRNG = void) if (isRandomAccessRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)));
 autorandomCover(Range, UniformRNG)(Ranger, auto ref UniformRNGrng)
 if (isRandomAccessRange!Range && isUniformRNG!UniformRNG);
 autorandomCover(Range)(Ranger)
 if (isRandomAccessRange!Range);
- Covers a given rangerin a random manner, i.e. goes through each element ofronce and only once, just in a random order.rmust be a random-access range with length.If no random number generator is passed torandomCover, the thread-global RNG rndGen will be used internally.Parameters:Range rrandom-access range to cover UniformRNG rng(optional) random number generator to use; if not specified, defaults to rndGen Returns:Range whose elements consist of the elements ofr, in random order. Will be a forward range if bothrandrngare forward ranges, an input range otherwise.Example: int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]; foreach (e; randomCover(a)) { writeln(e); } WARNING: If an alternative RNG is desired, it is essential for this to be a new RNG seeded in an unpredictable manner. Passing it a RNG used elsewhere in the program will result in unintended correlations, due to the current implementation of RNGs as value types.Example: int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ]; foreach (e; randomCover(a, Random(unpredictableSeed))) // correct! { writeln(e); } foreach (e; randomCover(a, rndGen)) // DANGEROUS!! rndGen gets copied by value { writeln(e); } foreach (e; randomCover(a, rndGen)) // ... so this second random cover { // will output the same sequence as writeln(e); // the previous one. } 
- structRandomSample(Range, UniformRNG = void) if (isInputRange!Range && (isUniformRNG!UniformRNG || is(UniformRNG == void)));
 autorandomSample(Range)(Ranger, size_tn, size_ttotal)
 if (isInputRange!Range);
 autorandomSample(Range)(Ranger, size_tn)
 if (isInputRange!Range && hasLength!Range);
 autorandomSample(Range, UniformRNG)(Ranger, size_tn, size_ttotal, auto ref UniformRNGrng)
 if (isInputRange!Range && isUniformRNG!UniformRNG);
 autorandomSample(Range, UniformRNG)(Ranger, size_tn, auto ref UniformRNGrng)
 if (isInputRange!Range && hasLength!Range && isUniformRNG!UniformRNG);
- Selects a random subsample out ofr, containing exactlynelements. The order of elements is the same as in the original range. Thetotallength ofrmust be known. Iftotalis passed in, thetotalnumber of sample is considered to betotal. Otherwise,RandomSampleusesr.length.Parameters:Range rrange to sample from size_t nnumber of elements to include in the sample; must be less than or equal to the totalnumber of elements inrand/or the parametertotal(if provided)size_t total(semi-optional) number of elements of rfrom which to select the sample (counting from the beginning); must be less than or equal to thetotalnumber of elements inritself. May be omitted ifrhas the .length property and the sample is to be drawn from all elements ofr.UniformRNG rng(optional) random number generator to use; if not specified, defaults to rndGen Returns:Range whose elements consist of a randomly selected subset of the elements ofr, in the same order as these elements appear inritself. Will be a forward range if bothrandrngare forward ranges, an input range otherwise.RandomSampleimplements Jeffrey Scott Vitter's Algorithm D (see Vitter 1984, 1987), which selects a sample of sizenin O(n) steps and requiring O(n) random variates, regardless of the size of the data being sampled. The exception to this is if traversing k elements on the input range is itself an O(k) operation (e.g. when sampling lines from an input file), in which case the sampling calculation will inevitably be of O(total).RandomSamplewill throw an exception iftotalis verifiably less than thetotalnumber of elements available in the input, or ifn>total. If no random number generator is passed torandomSample, the thread-global RNG rndGen will be used internally.Example: int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; // Print 5 random elements picked off from a foreach (e; randomSample(a, 5)) { writeln(e); } WARNING: If an alternative RNG is desired, it is essential for this to be a new RNG seeded in an unpredictable manner. Passing it a RNG used elsewhere in the program will result in unintended correlations, due to the current implementation of RNGs as value types.Example: int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; foreach (e; randomSample(a, 5, Random(unpredictableSeed))) // correct! { writeln(e); } foreach (e; randomSample(a, 5, rndGen)) // DANGEROUS!! rndGen gets { // copied by value writeln(e); } foreach (e; randomSample(a, 5, rndGen)) // ... so this second random { // sample will select the same writeln(e); // values as the previous one. } - const @property boolempty();
 @property ref autofront();
 voidpopFront();
 @property typeof(this)save();
 @property size_tlength();
- Range primitives.
- @property size_tindex();
- Returns theindexof the visited record.
 
Copyright Andrei Alexandrescu 2008 - 2009, Joseph Rushton Wakeling 2012.
 | Page generated by
Ddoc on (no date time)