Boost logo

Boost :

From: Darren Cook (darren_at_[hidden])
Date: 2004-06-22 22:38:20


I vote for these instructions to go near the top of the docs; I also
couldn't work out what I needed to do when I looked at Boost.Random a few
months back, but these instructions make it sound fairly simple.

What I wanted to do was generate a random number in the full range of a
integer template parameter, e.g. whether I used the template with unsigned
char, or a 128-bit integer. (in the end I decided to come back to this when
I needed that flexibility and implemented using 32-bit integers and the
standard library's srand48() and mrand48()).

So, can Boost.Random generate a random number to match the type?

Darren

> Assuming min and max are plain-vanilla integers, the
> following instructions:
>
> typedef boost::uniform_int<> UniformDist;
> UniformDist dist(min,max);
>
> produce an object named dist that holds your uniform
> distribution. The following instructions:
>
> typedef boost::mt19937 BaseRNG;
> BaseRNG rng;
>
> produce a "base pseudo-random number generator", which
> produces numbers along the *entire* range of integers
> (-2^31 to +2^31 or something like that).
> boost::mt19937 is one of many such generators provided
> by the library.
>
> The following instruction puts it all together and
> gives you the random integer generator you want:
>
> boost::variate_generator<BaseRNG&,UniformDist>
> your_generator(rng, dist);
>
> Note the ampersand; your program will fail silently if
> you omit it.
>
> The base random number generator (rng) holds the seed
> function; simply call
>
> rng.seed(42L);
>
> or whatever seed you want to provide.
>
> Finally, assuming you want to store your sequence in a
> vector<int>:
>
> vector<int> sample;
> for (int c = 0; c < desired_size; c++)
> {
> sample.push_back(your_generator());
> }


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk