PrevUpHomeNext

day-23: c++ STL: c++ Random Numbers


Let's ask a simple question: how to get a random number in c++?

The easiest way: std::random_device

#include <random>

int main()
{
	std::random_device rng;
	unsigned int aay = rng();
	// Now you got a random number: aay, it can be any unsigned int value
}

You will note that you always get the same value whatever how many times you run your program.

(Note that rng is an object of the class std::random_device, and rng() means calling the method .operator() of the object, an object of a class which defined method .operator() is named function object.)

To get a real randomized value every time you run your program, you need std::mt19937, it is a standard random number generator algorithm of c++ STL.

std::mt19937

std::mt19937 is the c++ random number engine mersenne-twister-engine algorithm. It is widely used to generate random numbers.

#include <random>

int main()
{
	std::random_device seed;
	std::mt19937 rng{seed()};
	unsigned int aay2 = rng();
}

You see that the object seed is an object of class std::random_device, and seed() is an integral number generated by seed, then that number is passed to the constructor of std::mt19937 to create the object rng. At last, use rng() to generate a random number aay2.

The generated random number can be used as the seed of std::mt19937 again, and any integer numbers can be used as its seed too

std::mt19937 rng1{3456};	// 3456 is used as seed
std::mt19937 rng1{6543};
std::mt19937 rng2{rng1()};	// rng1() is used as the seed of rng2
std::random_device rng1;
std::mt19937 rng2{rng1()};	// rng1() is used as the seed of rng2
std::mt19937 rng3{rng2()};	// rng2() is used as the seed of rng3

std::mt19937_64

std::mt19937_64 is the 64-bit-algorithm of std::mt19937, both std::mt19937_64 and std::mt19937 creates the same bit type of random number.

#include <random>
#include <iostream>

int main()
{
	auto rng1 = std::random_device{};

	// rng1() is used as seed, rng2() can be used as seed again.
	auto rng2 = std::mt19937_64{rng1()};

	auto random_value = rng2();

	std::cout << random_value << std::endl;
}







Written on Dec 09, 2024

Back to index

Index

cpp/c++

c++ std::exception:

std::cout.write(err.data(), err.size());

std::cout << std::endl;

caught:

  ===================================
  #  The c++ programming language.  #
  #                                 #
  #  Join c++ Discord: yZcauUAUyC   #
  #  Deck                           #
  ===================================

Home: cppfx.xyz

K


PrevUpHomeNext