2.5.4 Random

What was the problem

Getting random numbers in C++ was historically done by using functions from the C library. First we initialized the a global generator via a call to srand() then the values were generated via rand().

Unfortunately this generator was known for being a quite poor one.

How the Problem is Solved

PIC <random>

This has been greatly improved in C++11. For the initialization, we now have std::random_device to access a hardware-based generator6, then there are many pseudo-random number generators, std::mt19937 being a quite popular one.

int main() 
{ 
  // The random device will get a random value from the system. It is 
  // certainly the best random source we can have here. 
  std::random_device seed; 
 
  // This is a pseudo-random number generator, here initialized by 
  // a value obtained from the random device. 
  std::mt19937 generator(seed()); 
 
  // Finally this distribution will project the random values in the 
  // [1, 24] range with equiprobability for each value. 
  std::uniform_int_distribution<int> range(1, 10); 
 
  for (int i = 0; i != 1000; ++i) 
    printf("%d\n", range(generator)); 
 
  return 0; 
}

Unfortunately the generators available in the standard library are known to be both inefficient and not very good at randomness. As an alternative, we can check for a permuted congruential generator (PCG) [O’N14], at https://www.pcg-random.org/.

6If there is one, otherwise it would be software-based.