| marp | true |
|---|---|
| math | katex |
| theme | custom-theme |
| footer |
- How to generate random numbers in modern C++
- What's wrong with
rand()
πΊ Watch the related YouTube video!
- π¨ - Style recommendation
- π - Software design recommendation
- π± - Not a good practice! Avoid in real life!
- β - Good practice!
- β - Whatever is marked with this is wrong
- π¨ - Alert! Important information!
- π‘ - Hint or a useful exercise
- πΌ1οΈβ£7οΈβ£ - Holds for this version of C++(here,
17) and above - π½1οΈβ£1οΈβ£ - Holds for versions until this one C++(here,
11)
Style (π¨) and software design (π) recommendations mostly come from Google Style Sheet and the CppCoreGuidelines
- Random numbers should be hard to predict (under the definition of "hard")
- Mostly, we generate pseudo-random numbers instead
- There are multiple algorithms for this:
- Linear congruential generator - Fast and small storage
- Lagged Fibonacci generator - Very fast, uses more storage
- Mersenne Twister - Slower, uses more storage but generates very high quality pseudo random numbers
- We will not go into details here!
- If you want to learn more, you can:
- Read a book Random Numbers and Computers
- Read this technical report for a slightly advanced intro
- πΌ1οΈβ£1οΈβ£ Include
<random> - β There is a great summary of pseudo random number generation on cppreference.com
- Implements all the algorithms listed on previous slide
- Here is a summary of how it works:
- We need a "random device" that is our source of non-deterministic uniform (maybe pseudo-) random numbers
- We pass this device into a "random number engine" from the previous slide
- We pass this engine into a "random number distribution" which generates the resulting numbers we want
#include <iostream>
#include <random>
int main() {
std::random_device random_device;
std::mt19937 random_engine{random_device()};
std::uniform_real_distribution distribution{23.0, 42.0};
for (auto i = 0; i < 5; ++i) {
std::cout << distribution(random_engine) << std::endl;
}
return 0;
}This gives an output that looks smth like this:
33.9856
30.8976
40.8357
37.9964
27.8459
- It is available from the
<cstdlib>header rand()is a C function (not C++)- The only option before
C++11 - π± Let's see how it's typically used:
// Somewhere in main std::srand(seed); // Initialize random seed int random_variable = std::rand();
- π± It uses global state (seed is set globally)
- The quality of the generated random sequence is not guaranteed
- β
Always use methods from
<random>instead!
