marp | math | theme | footer |
---|---|---|---|
true |
katex |
custom-theme |
- 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!