C++11C++14C++17Learn C++Numerics

Introduction to Random Number Generation in Modern C++

Every implementation of the C++ Standard Library like one included to Embarcadero RAD Studio C++ compilers provides two ways for (pseudo-)random numbers generation: old-fashioned facilities from <cstdlib> and modern facilities provided by <random>.

Facilities from <cstdlib>

There are two very simple functions provided by the C random library: std::srand() and std::rand(). The former seeds the pseudo-random number generator and the later generates a pseudo-random number from range [0, RAND_MAX], where RAND_MAX is an implementation defined integer constant that is guaranteed be at least 32767.
Please keep in mind, that a sequence of random numbers from the same seed is repeatable! Hence, it’s important to seed the random number generator by some new integer value, such as the time point picked up from system clock, before calling of std::rand().

Facilities from <random>

There are four categories of entities in modern part (available since C++11) of random number library: uniform random number generators, random number engines, random number engine adaptors, and random number distributions:

Uniform random number generator is intended to yield unsigned integer values in the range of possible results.

Random number engine is a uniform random number generator with a state determined by a seed.

Random number engine adaptor is a random number engine intended to transform values from another random number engine to produce values with modified randomness properties by using some algorithm.

Random number distribution is a function to yield values that are distributed according to an associated mathematical probability density function.

Binding a number distribution to an engine yields a generator that produces a sequence of values according to a distribution. For example, let’s bind Normal Distribution to a default random engine (which provides the behavior for relatively casual, inexpert, and/or lightweight use):

The visualization of the output produced by the program above might looks like the following:


Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome C++ content in your inbox, every day.

We don’t spam! Read our privacy policy for more info.

Related posts
C++Learn C++Videos

Learn C++ With Design Patterns For Handling/Reporting Errors In C++: Parallel Algorithms And Executors by Mark Hoemmen (CPPCon 2020) Videos

C++Introduction to C++Learn C++

Learn To Use Break And Continue In Loops With C++

C++Introduction to C++Learn C++

Learn To Define And Use Arrays In C++

C++Learn C++Videos

Learn C++ With Back to Basics: Design Pattern by Mike Shah (CPPCon 2020) Video