RandomSource

© 2011 John Abbott
GNU Free Documentation License, Version 1.2



CoCoALib Documentation Index

User documentation for RandomSource

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.

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.

There are four functions for generating random values from a RandomSource:

    RandomBool(RndSrc)
    RandomLong(RndSrc)
    RandomLong(RndSrc, lwb, upb)   // in range lwb..upb (both ends included)
    RandomZZ(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);

For convenience, there is a global RandomSource but using it will make your code thread-unsafe; a cleaner way is to pass the random source as an argument. A reference to the global random source may be obtained by calling GlobalRandomSource() -- see GlobalManager.

Maintainer documentation

Mostly quite straightforward since almost all the work is done by GMP.

RandomLong(RndSrc, lwb, upb) is a bit messy for two reasons: (a) CoCoALib uses signed longs while GMP uses unsigned longs; (b) the case when (lwb,upb) specify the whole range of representable longs requires special handling.

Bugs, shortcomings and other ideas

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.

Main changes

2011