Ch12.1: C++ Random Engines

Overview

C++ provides several random number engines in the <random> header. These engines generate pseudo-random sequences of numbers based on an initial seed. The most commonly used engines are:

The Mersenne Twister engines (mt19937 and mt19937_64) are the most widely used due to their excellent statistical properties and long period (219937-1).

Using std::mt19937_64

The 64-bit Mersenne Twister is suitable for most applications requiring random numbers. Here's how to use it:


#include <fast_io.h>
#include <random>

int main() {
    using namespace ::fast_io::io;

    // Create an engine with default seed
    // WARNING: This is predictable! Always use proper seeding.
    ::std::mt19937_64 eng;

    // Generate random numbers
    for (::std::size_t i{}; i != 10; ++i) {
        println("Random: ", eng());
    }
}
Warning: Using the default constructor creates a predictable sequence. The default seed is fixed (typically 5489u), so every program run produces the same "random" numbers. Always use proper seeding with ::std::seed_seq (see Ch12.4).

Engine Properties

All C++ random engines provide these methods:

Method Description
operator()() Generates the next random number in the sequence
min() Returns the minimum value the engine can produce
max() Returns the maximum value the engine can produce
seed() Reseeds the engine with a new seed value
discard(z) Advances the engine state by z steps without generating output

Engine Comparison

Engine Output Type Period Use Case
::std::mt19937 32-bit unsigned 219937-1 General purpose, games, simulations
::std::mt19937_64 64-bit unsigned 219937-1 General purpose, larger state space
::std::minstd_rand 32-bit unsigned 231-1 Simple, fast, but lower quality
::std::ranlux48 48-bit unsigned ~10171 High-quality, slower

Key Takeaways