liveBook · Manning

Random number

As explained in Learn C++ by Example

A random number is a value generated by a process intended to provide unpredictable or pseudorandom outcomes according to a specified domain.

A random number supports a guessing game by producing a value within a chosen range. C++ sets this up with a seed, an engine, and a distribution. section 3.0 section 3.2.2

A single generated value follows this pattern:

  • Seed an engine with std::random_device. section 3.2.2
  • Create an std::mt19937 engine and a uniform_int_distribution<int> for the desired range. section 3.2.2
  • Call dist(engine); repeat the call without repeating setup when more values are needed. section 3.2.2

Random prime generation

To generate a prime, draw values from 1 to 99,999 and keep trying until is_prime accepts one. This filtering technique is rejection sampling. section 3.3.3

Listing 3.9 Generating a single random number
int some_random_number()
{
    std::random_device rd;                              #1
    std::mt19937 engine(rd());                          #2
    std::uniform_int_distribution<int> dist(1, 100);    #3
    return dist(engine);                                #4
}

View the complete C++ function for generating one uniformly distributed integer from 1 to 100. section 3.2.2

How Learn C++ by Example covers it

How deep it goes
Explains seed, engine, distribution, repeated draws, and rejection sampling, but stops short of advanced distribution design.
Examples
Demonstrates uniform integers from 1 to 100 and prime numbers from 1 to 99,999.
What you can do after
Build it from scratch with C++ engines and distributions, then apply rejection sampling to generate values with a required property.
How it connects
Connects random number generation with number-guessing games, random_device, mt19937, uniform_int_distribution, and rejection sampling.

Also explained in

Compare how 4 books explain random number →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.