Random Numbers in C++

The <random> library in C++ provides pseudorandom number generation.

#include <iostream>
#include <random>
#include <ctime>

int main() {
    // Create a random number generator
    std::random_device rd;
    std::mt19937 gen(rd());

    // For example, std::uniform_int_distribution generates a random int n,
    // 0 <= n < 100.
    std::uniform_int_distribution<> dis(0, 99);
    std::cout << dis(gen) << "," << dis(gen) << std::endl;

    // std::uniform_real_distribution generates a float f,
    // 0.0 <= f < 1.0.
    std::uniform_real_distribution<> dis_float(0.0, 1.0);
    std::cout << dis_float(gen) << std::endl;

    // This can be used to generate random floats in
    // other ranges, for example 5.0 <= f' < 10.0.
    std::uniform_real_distribution<> dis_float_range(5.0, 10.0);
    std::cout << dis_float_range(gen) << "," << dis_float_range(gen) << std::endl;

    // If you want a known seed, you can set it explicitly
    std::mt19937 gen_seeded(42);
    std::cout << dis(gen_seeded) << "," << dis(gen_seeded) << std::endl;

    // Using the same seed will produce the same sequence of random numbers
    std::mt19937 gen_seeded_2(42);
    std::cout << dis(gen_seeded_2) << "," << dis(gen_seeded_2) << std::endl;

    return 0;
}

To compile and run the program:

$ g++ -std=c++11 random_numbers.cpp -o random_numbers
$ ./random_numbers
68,56
0.809023
5.84013,6.93706
94,49
94,49

Some of the generated numbers may be different when you run the sample.

The <random> library in C++ provides a wide range of random number generators and distributions. You can check the C++ reference for more information on other random quantities that C++ can provide.

In this example:

  1. We use std::random_device to seed our random number generator.
  2. std::mt19937 is a Mersenne Twister generator, which is a high-quality random number generator.
  3. std::uniform_int_distribution and std::uniform_real_distribution are used to generate random integers and floating-point numbers respectively.
  4. We demonstrate how to generate numbers in specific ranges.
  5. We also show how to use a fixed seed for reproducible random number sequences.

Remember that the C++ random number facilities are more type-safe and generally of higher quality than the older C-style rand() function.