A RandomSource
is a general source of (pseudo-)randomness: you can
use it to produce random bits, random machine integers, and random big
integers. For an alternative way of generating random values, see
RandomBoolStream
, RandomLongStream
, and RandomZZStream
;
these specialized functions may be a little faster.
There are random functions without a RandomSource
argument
(see below and the first example) which call implicitly
GlobalRandomSource()
which is stored in GlobalManager
.
This means you probably do not need to know about this class!
The constructor for RandomSource
expects a single integer argument
which is the initial "seed" (i.e. it determines the initial
state); it may also be called with no argument in which case the seed
value is taken to be 1.
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 reseed
function documented below.
For convenience, there is a global RandomSource
but using it will
make your code thread-unsafe. A reference to the global random source may be obtained by
calling GlobalRandomSource()
-- see GlobalManager
.
These are the functions for generating random values from the global source:
RandomBool()
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 RandomSource
:
RandomBool(RndSrc)
RandomLong(RndSrc, lwb, upb)
-- in range lwb..upb (both ends included)
RandomBigInt(RndSrc, lwb, upb)
-- in range lwb..upb (both ends included)
A RandomSource
may be reseeded at any time; immediately after reseeding
it will generate the same random sequence as a newly created RandomSource
initialized with that same seed. The seed must be an integer value.
reseed(RndSrc, seed)
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.
2012
RandomLong(src)
(i.e. with no range)
RandomBool()
, RandomLong(a,b)
, RandomBigInt(a,b)
(i.e. with no RandomSource
)
2011