Random Number Generation in C++
Highwayman (1320)

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?!?


int random_number = gen(); 

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
Highwayman (1320)

@MatthewDoan1 I have heard time and again that rand is pretty bad, and also you would have to figure out yourself how to make a random number within a range which isn’t biased, for example modding a random number will generally not produce an unbiased result because our random numbers aren’t arbitrarily large, they are already produced within a range which makes it more likely you get certain numbers in that range. Also the periodicity of the generators is much bigger.