Random Number Generation in C++
h
Highwayman (399)

In the past, the only standard we had for random number generation was rand() and srand() in the c library, but with the introduction of the c++11 standard, we now have a newer and much better way for random number generation: the <random> header! Yay! I know so exciting.
I’m going to show some of the ways you can make random numbers.

Step 1: Initializating a generator object,

This is easy. You have several different PRNG(pseudorandom number generator) classes to choose from, but for this tutorial I will be using the mt19937 generator class.
When declaring a PRNG object like mt19937, the generator is seeded with a special number that it uses to kinda 'kick off' it’s generation. Kinda like with srand(), most people will use the time to initialize the object.

#include <chrono>
#include <random>

int main () {
  unsigned seed  = std::chrono::system_clock::now().time_since_epoch().count();

  std::mt19937 rnd (seed);
}

In my opinion, this is the most ridiculous and excessive initialization I’ve ever seen in my life.
I’m just going to use 0.

#include <random>

int main() {
  std::mt19937 gen(0);
}

Step 2: use it.

Woah! The tutorial’s already done?!?

yes.

int random_number = gen(); 

Edit:
Aw man wait I missed the best part of the new <random> header: unbiased distribution!

For this you just make a distribution object. You can either make one for real numbers (like -1.84 or 6.6) or integers (like 1 or -3)
To do this you just initialize the object with the range that the number should be in between, along with the type of the random numbers as a template argument like so..

#include <random>

int main() {
  std::uniform_int_distribution dist<int> (1,100);
}

And then to use the distribution, you just pass the generator that you declared before:

int random_number = dist(gen); // make a random number from 1 to 100 
You are viewing a single comment. View All
MatthewDoan1 (234)

@Highwayman Wow, so it took that long for C++ to have an actually decent random algorithm?