Next: , Previous: , Up: Random Number Generators   [Contents][Index]


9.3 Seeding a random number generator

You may seed a random number generator using the member function seed(unsigned int). By default, all random number generators share the same underlying integer random number generator. So seeding one generator will seed them all. (Note: you can create generators with their own internal state; see the sections below). You should generally only seed a random number generator once, at the beginning of a program run.

Here is an example of seeding with the system clock:

#include <random/uniform.h>
#include <time.h>

using namespace ranlib;

int main()
{
    // At start of program, seed with the system time so we get
    // a different stream of random numbers each run.
    Uniform<float> x;
    x.seed((unsigned int)time(0));

    // Rest of program
    ...
}

Note: you may be tempted to seed the random number generator from a static initializer. Don’t do it! Due to an oddity of C++, there is no guarantee on the order of static initialization when templates are involved. Hence, you may seed the RNG before its constructor is invoked, in which case your program will crash. If you don’t know what a static initializer is, don’t worry – you’re safe!