D Programming Language 2.0

- Comments
- D
- Search
- Home

Last update Sat Feb 14 12:00:06 2009

# 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 contributed 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,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.
  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

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

struct UniformDistribution(NumberType,string boundaries = "[)"
;

  Generates uniformly-distributed numbers within a range using an external generator. 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 [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 between a and b. The bounds of the interval are controlled by the template argument, e.g. UniformDistribution!(double, "[]")(0, 1) generates numbers in the interval [0.0, 1.0].
  ResultType a();
    Returns the left bound of the random value generated.
  ResultType b();
    Returns the the right bound of the 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.
T1 uniform(T1, string boundaries = "[)", UniformRandomNumberGenerator, T2
(ref UniformRandomNumberGenerator gen, T1 a, T2 b); )
  Convenience function that generates a number in an interval by forwarding to UniformDistribution!(T, boundaries)(a, b).next.
  Example:

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

void randomShuffle(T, SomeRandomGen)(T[] array, ref SomeRandomGen r);
  Shuffles elements of array using r as a shuffler.
size_t dice(R)(ref R rnd, double[] proportions...);
  Throws 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

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.
)
Copyright © 1999-2009 by Digital Mars, All Rights Reserved | Page generated by Ddoc.