Skip to content

Latest commit

 

History

History
109 lines (97 loc) · 3.76 KB

random_numbers.md

File metadata and controls

109 lines (97 loc) · 3.76 KB
marp math theme footer
true
katex
custom-theme

Random number generation

Today:

  • How to generate random numbers in modern C++
  • What's wrong with rand()

📺 Watch the related YouTube video!


Special symbols used in slides

  • 🎨 - 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


What are random numbers?

bg 60%


What are random numbers?


But how do I use it?

  • 🔼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:
    1. We need a "random device" that is our source of non-deterministic uniform (maybe pseudo-) random numbers
    2. We pass this device into a "random number engine" from the previous slide
    3. We pass this engine into a "random number distribution" which generates the resulting numbers we want

Let's see it in practice

#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

What's wrong with rand()?

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

bg