RandomSource is a general source of (pseudo-)randomness: you can
use it to produce random bits, random machine integers, and random big
integers. For alternative ways of generating random values, see
these specialized functions may be a little faster.
The constructor for
RandomSource has an optional single integer argument
which is the initial seed -- it determines the initial
state of the generator. If you do not give a seed, the default is 0.
RandomSource RndSrc; // seeded with 0 by default RandomSource RndSrc(n); // seeded with n
If you create more than one
RandomSource object with the same
seed, they will each produce exactly the same sequence of values. In
particular, to obtain different results each time a program is run,
you can, for instance, seed the generator with the system time (e.g.
by supplying as argument
time(0)); this is likely desirable unless
you're trying to debug a randomized algorithm. See also the
function documented below.
For convenience, there is a global
RandomSource object (living
GlobalManager); you can get a reference to it by calling
GlobalRandomSource(). It is very convenient, and is probably just
what you want in a simple program, but using it will make your code thread-unsafe.
These are the convenient (thread-unsafe) functions for generating
random values from
RandomLong(lwb, upb)-- in range lwb..upb (both ends included)
RandomBigInt(lwb, upb)-- in range lwb..upb (both ends included)
A cleaner way is to pass the random source as an argument: these are
the functions for generating random values from a specified random source
RandomLong(RndSrc, lwb, upb)-- in range lwb..upb (both ends included)
RandomBigInt(RndSrc, lwb, upb)-- in range lwb..upb (both ends included)
RandomSource object may be reseeded at any time; immediately after reseeding
it will generate the same random sequence as a newly created
initialized with that same seed. The seed must be an integer value.
Note about thread-safety: the various operations on a fixed
RandomSource object are not thread-safe; to achieve thread safety,
you should use different objects in different threads. So, it is best
not to use
GlobalRandomSource() in a multi-threaded environment.
Mostly quite straightforward since almost all the work is done by GMP.
RandomLong(RndSrc, lwb, upb) is a bit messy for two reasons:
The printing function gives only partial information; e.g. two RandomSource objects with different internal states might be printed out identically.
The implementation simply calls the GMP pseudo-random generator; this generator is deterministic (so always produces the same sequence), but if you change versions of GMP, the sequence of generated values may change. You will have to read the GMP documentation to know more.
RandomLong(src)(i.e. with no range)
RandomBigInt(a,b)(i.e. with no