Random numbers are required in a number of different problem domains, such
as

numerics (simulation, Monte-Carlo integration)

games (non-deterministic enemy behavior)

security (key generation)

testing (random coverage in white-box tests)

The Boost Random Number Generator Library provides a framework for random
number generators with well-defined properties so that the generators can
be used in the demanding numerics and security domains. For a general introduction
to random numbers in numerics, see

A uniform random number generator provides a sequence of random numbers
uniformly distributed on a given range. The range can be compile-time fixed
or available (only) after run-time construction of the object.

The tight lower bound of some (finite) set S is the
(unique) member l in S, so that for all v in S, l <= v holds. Likewise,
the tight upper bound of some (finite) set S is the
(unique) member u in S, so that for all v in S, v <= u holds.

In the following table, X denotes a number generator class returning objects
of type T, and v is a const value of X.

tight lower bound on the set of all values returned by operator().
The return value of this function shall not change during the
lifetime of the object.

v.max()

T

if std::numeric_limits<T>::is_integer, tight upper bound
on the set of all values returned by operator(), otherwise, the smallest representable
number larger than the tight upper bound on the set of all values
returned by operator(). In any case, the return value
of this function shall not change during the lifetime of the
object.

The member functions min,
max, and operator()
shall have amortized constant time complexity.

Rationale: The range description with min and max serves two purposes.
First, it allows scaling of the values to some canonical range, such
as [0..1). Second, it describes the significant bits of the values, which
may be relevant for further processing.

The range is a closed interval [min,max] for integers, because the underlying
type may not be able to represent the half-open interval [min,max+1).
It is a half-open interval [min, max) for non-integers, because this
is much more practical for borderline cases of continuous distributions.

A non-deterministic uniform random number generator is a UniformRandomNumberGenerator
that is based on some stochastic process. Thus, it provides a sequence
of truly-random numbers. Examples for such processes are nuclear decay,
noise of a Zehner diode, tunneling of quantum particles, rolling a die,
drawing from an urn, and tossing a coin. Depending on the environment,
inter-arrival times of network packets or keyboard events may be close
approximations of stochastic processes.

The class random_device
is a model for a non-deterministic random number generator.

Note

This type of random-number generator is useful for security applications,
where it is important to prevent an outside attacker from guessing the
numbers and thus obtaining your encryption or authentication key. Thus,
models of this concept should be cautious not to leak any information,
to the extent possible by the environment. For example, it might be advisable
to explicitly clear any temporary storage as soon as it is no longer
needed.

A pseudo-random number generator is a UniformRandomNumberGenerator
which provides a deterministic sequence of pseudo-random numbers, based
on some algorithm and internal state. Linear
congruential and inversive
congruential generators are examples of such pseudo-random
number generators. Often, these generators are very sensitive to
their parameters. In order to prevent wrong implementations from being
used, an external testsuite should check that the generated sequence and
the validation value provided do indeed match.

Donald E. Knuth gives an extensive overview on pseudo-random number generation
in his book "The Art of Computer Programming, Vol. 2, 3rd edition,
Addison-Wesley, 1997". The descriptions for the specific generators
contain additional references.

Note

Because the state of a pseudo-random number generator is necessarily
finite, the sequence of numbers returned by the generator will loop eventually.

In addition to the UniformRandomNumberGenerator
requirements, a pseudo-random number generator has some additional requirements.
In the following table, X
denotes a pseudo-random number generator class returning objects of type
T, x
is a value of T, u is a value of X,
and v is a const value
of X.

Table 21.2. PseudoRandomNumberGenerator requirements

expression

return type

pre/post-condition

X()

-

creates a generator in some implementation-defined state. Note:
Several generators thusly created may possibly produce dependent
or identical sequences of random numbers.

X(...)

-

creates a generator with user-provided state; the implementation
shall specify the constructor argument(s)

u.seed(...)

void

sets the current state according to the argument(s); at least
functions with the same signature as the non-default constructor(s)
shall be provided.

Note

The seed member function is similar to the assign member function in
STL containers. However, the naming did not seem appropriate.

Classes which model a pseudo-random number generator shall also model
EqualityComparable,
i.e. implement operator==.
Two pseudo-random number generators are defined to be equivalent
if they both return an identical sequence of numbers starting from a given
state.

Classes which model a pseudo-random number generator should also model
the Streamable concept, i.e. implement operator<< and operator>>. If so, operator<< writes all current state of the
pseudo-random number generator to the given ostream
so that operator>>
can restore the state at a later time. The state shall be written in a
platform-independent manner, but it is assumed that the locales
used for writing and reading be the same. The pseudo-random number generator
with the restored state and the original at the just-written state shall
be equivalent.

Classes which model a pseudo-random number generator should also model
the CopyConstructible
and Assignable concepts.
However, note that the sequences of the original and the copy are strongly
correlated (in fact, they are identical), which may make them unsuitable
for some problem domains. Thus, copying pseudo-random number generators
is discouraged; they should always be passed by (non-const) reference.

This type of random-number generator is useful for numerics, games and
testing. The non-zero arguments constructor(s) and the seed()
member function(s) allow for a user-provided state to be installed in
the generator. This is useful for debugging Monte-Carlo algorithms and
analyzing particular test scenarios. The Streamable concept allows to
save/restore the state of the generator, for example to re-run a test
suite at a later time.

A random distribution produces random numbers distributed according to
some distribution, given uniformly distributed random values as input.
In the following table, X
denotes a random distribution class returning objects of type T, u
is a value of X, x is a (possibly const) value of X, and e
is an lvalue of an arbitrary type that meets the requirements of a UniformRandomNumberGenerator,
returning values of type U.

subsequent uses of u
do not depend on values produced by any engine prior to invoking
reset.

constant

u(e)

T

the sequence of numbers returned by successive invocations with
the same object e
is randomly distributed with some probability density function
p(x)

amortized constant number of invocations of e

os<<x

std::ostream&

writes a textual representation for the parameters and additional
internal data of the distribution x
to os. post:
The os.fmtflags and fill character
are unchanged.

O(size of state)

is>>u

std::istream&

restores the parameters and additional internal data of the distribution
u. pre: is provides a textual representation
that was previously written by operator<< post: The is.fmtflags are unchanged.

O(size of state)

Additional requirements: The sequence of numbers produced by repeated invocations
of x(e) does
not change whether or not os<<x
is invoked between any of the invocations x(e).
If a textual representation is written using os<<x
and that representation is restored into the same or a different object
y of the same type using
is>>y, repeated invocations of y(e) produce the same sequence of random numbers
as would repeated invocations of x(e).

This library provides several pseudo-random
number generators. The quality of a pseudo
random number generator crucially depends on both the algorithm and
its parameters. This library implements the algorithms as class templates
with template value parameters, hidden in namespaceboost::random. Any particular choice of parameters
is represented as the appropriately specializing typedef
in namespaceboost.

Pseudo-random
number generators should not be constructed (initialized) frequently
during program execution, for two reasons. First, initialization requires
full initialization of the internal state of the generator. Thus, generators
with a lot of internal state (see below) are costly to initialize. Second,
initialization always requires some value used as a "seed" for
the generated sequence. It is usually difficult to obtain several good seed
values. For example, one method to obtain a seed is to determine the current
time at the highest resolution available, e.g. microseconds or nanoseconds.
When the pseudo-random
number generator is initialized again with the then-current time as
the seed, it is likely that this is at a near-constant (non-random) distance
from the time given as the seed for first initialization. The distance could
even be zero if the resolution of the clock is low, thus the generator re-iterates
the same sequence of random numbers. For some applications, this is inappropriate.

Note that all pseudo-random
number generators described below are CopyConstructible
and Assignable. Copying
or assigning a generator will copy all its internal state, so the original
and the copy will generate the identical sequence of random numbers. Often,
such behavior is not wanted. In particular, beware of the algorithms from
the standard library such as std::generate.
They take a functor argument by value, thereby invoking the copy constructor
when called.

The following table gives an overview of some characteristics of the generators.
The cycle length is a rough estimate of the quality of the generator; the
approximate relative speed is a performance measure, higher numbers mean
faster random number generation.

As observable from the table, there is generally a quality/performance/memory
trade-off to be decided upon when choosing a random-number generator. The
multitude of generators provided in this library allows the application programmer
to optimize the trade-off with regard to his application domain. Additionally,
employing several fundamentally different random number generators for a
given application of Monte Carlo simulation will improve the confidence in
the results.

If the names of the generators don't ring any bell and you have no idea which
generator to use, it is reasonable to employ mt19937
for a start: It is fast and has acceptable quality.

Note

These random number generators are not intended for use in applications
where non-deterministic random numbers are required. See random_device
for a choice of (hopefully) non-deterministic random number generators.

In addition to the random
number generators, this library provides distribution functions which
map one distribution (often a uniform distribution provided by some generator)
to another.

Usually, there are several possible implementations of any given mapping.
Often, there is a choice between using more space, more invocations of the
underlying source of random numbers, or more time-consuming arithmetic such
as trigonometric functions. This interface description does not mandate any
specific implementation. However, implementations which cannot reach certain
values of the specified distribution or otherwise do not converge statistically
to it are not acceptable.