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.

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!

Examples

Constructors

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.

Operations

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:

A cleaner way is to pass the random source as an argument: these are the functions for generating random values from a RandomSource:

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.

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:

  1. CoCoALib uses signed longs while GMP uses unsigned longs;
  2. 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

2012