C++11 notes – <random>

The random library introduced in Boost, put into TR1, and now part of C++11, is awesome. This is one of the must-use bits of the C++ Standard Library. It’s solid and pretty fast. My recommendation is that, unless you are really an expert, you use <random> for your random number needs, and be done with it.

The 10-second introduction to the theory of <random>

Engines are sources of random numbers; an engine returns unsigned integer numbers uniformly distributed in a range between a predefined min and a predefined max. Typically, this is the min and max of the unsigned integer range.

engine e;
v = e();

Distributions turn the uniformly distributed values into a desired distribution; linear, normal/gaussian, exponential, gamma, Bernouilli, etc.

dist d;
v = d(e());

That’s it! Well, the devil is in the details, but the details aren’t much more daunting than that – you need to pick an engine and a distribution, and you probably want to seed the engine, and you may need to worry about thread-safety. And of course, the standard uses much longer names than engine and dist.

Oh, and always use a distribution. It will do the mapping of random integers into your desired range properly.

A list of references to <random>

Random Number Generation in C++11 is the proposal to put <random> in the C++11 standard library. It’s also pretty readable. It has good sample code. If you’re going to read one thing on <random>, read this, because it clearly explains what engines are and what distributions are.

The C++ Standard Library: A Tutorial and Reference, Second Edition, by Nicolai M. Josuttis, has a chapter on <random> that’s pretty good.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>