D Programming Language 2.0

- Comments
- D
- Search
- Home

Last update Thu Oct 28 17:54:35 2010

# 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 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);

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.

License:
Boost License 1.0.

Authors:
Andrei Alexandrescu

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.

Copyright Andrei Alexandrescu 2008 - 2009. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at

http:
//www.boost.org/LICENSE_1_0.txt)

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

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

  UIntType min;
    Lowest generated value (1 if c == 0, 0 otherwise).

  UIntType max;
    Highest generated value (modulus - 1).

  UIntType multiplier;
  UIntType increment;
  UIntType modulus;
    The parameters of this distribution. The random number is x = (x * multipler + increment) % modulus.

  this(UIntType x0);
    Constructs a LinearCongruentialEngine generator seeded with x0.

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

  void popFront();
    Advances the random sequence.

  UIntType front();
    Returns the current number in the random sequence.

  typeof(this) save();

  bool empty;
    Always false (random generators are infinite ranges).

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

alias MinstdRand0;
alias MinstdRand;
  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.

  Example:

      // 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

struct MersenneTwisterEngine(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);
  The Mersenne Twister generator.

  size_t wordSize;
    Parameter for the generator.

  UIntType min;
    Smallest generated value (0).

  UIntType max;
    Largest generated value.

  UIntType defaultSeed;
    The default seed value.

  this(UIntType value);
    Constructs a MersenneTwisterEngine object.

  void seed(UIntType value = defaultSeed);
    Seeds a MersenneTwisterEngine object.

  void popFront();
    Advances the generator.

  UIntType front();
    Returns the current random value.

  typeof(this) save();

  bool empty;
    Always false.

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.front; // same for each run
      // Seed with an unpredictable value
      gen.seed(unpredictableSeed);
      n = gen.front; // different across runs

uint 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.front;
      ...

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

Random 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.

CommonType!(T1,T2) uniform(string boundaries = "[)", T1, T2, UniformRandomNumberGenerator
(T1 a, T2 b, ref UniformRandomNumberGenerator urng);

  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.

  Example:

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

CommonType!(T1,T2) uniform(string boundaries = "[)", T1, T2
(T1 a, T2 b); )
  As above, but uses the default generator rndGen.

F[] uniformDistribution(F = double)(size_t n, F[] useThis = null);
  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.

void randomShuffle(Range, RandomGen = Random)(Range r, ref RandomGen gen = rndGen);
  Shuffles elements of r using r as a shuffler. r must be a random-access range with length.

size_t dice(R, Num)(ref R rnd, Num[] proportions...);
size_t dice(R, Range)(ref R rnd, Range proportions);
size_t dice(Num)(Num[] proportions...);
size_t dice(Range)(Range proportions);
  Rolls a dice with relative probabilities stored in proportions. Returns the index in proportions that was chosen.

  Example:

      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 30% of the time,
                                 // and 2 10% of the time

struct RandomCover(Range,Random);
RandomCover!(Range,Random) randomCover(Range, Random)(Range r, Random rnd);
  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.

  Example:

      int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];
      auto rnd = Random(unpredictableSeed);
      foreach (e; randomCover(a, rnd))
      {
          writeln(e);
      }

struct RandomSample(R);
RandomSample!(R) randomSample(R)(R r, size_t n, size_t total);
RandomSample!(R) randomSample(R)(R r, size_t n);
  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.

  If the number of elements is not exactly total, RandomSample throws an exception. This is because total is essential to computing the probability of selecting elements in the range.

  Example:

      int[] a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];
      // Print 5 random elements picked off from r
      foreach (e; randomSample(n, 5))
      {
          writeln(e);
      }

  this(R input, size_t howMany);
  this(R input, size_t howMany, size_t total);
    Constructor.

  const bool empty();
  void popFront();
  typeof(this) save();
  size_t length();
    Range primitives.

  size_t index();
    Returns the index of the visited record.

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.

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

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

)
Copyright Andrei Alexandrescu 2008 - 2009. | Page generated by Ddoc.