C++ - Random Numbers
Overview
Estimated time: 40–60 minutes
Generate reproducible random numbers using engines and distributions. Learn seeding, ranges, and common pitfalls.
Learning Objectives
- Use std::mt19937 and distributions (uniform_int_distribution, uniform_real_distribution).
- Seed properly and reproduce sequences for tests.
Prerequisites
Uniform integers
#include
#include
int main(){
std::mt19937 rng(123); // fixed seed
std::uniform_int_distribution dist(1,6);
for(int i=0;i<3;++i) std::cout << dist(rng) << ' ';
}
Uniform reals
#include
#include
int main(){
std::random_device rd; // non-deterministic seed source
std::mt19937 rng(rd());
std::uniform_real_distribution dist(0.0, 1.0);
std::cout << dist(rng) << "\n";
}
Common Pitfalls
- Seeding with time repeatedly in a loop; create one engine and reuse it.
- Using rand()—prefer
facilities.
Checks for Understanding
- How do you get repeatable results?
- Why avoid std::rand?
Show answers
- Seed the engine with a fixed value.
- rand has poor quality and non-portable ranges;
provides robust engines and distributions.
Exercises
- Roll two dice 100 times and compute the distribution of sums.
- Generate normally distributed numbers and compute mean/stddev.