Choosing the right random number distribution depends on the characteristics of the random numbers you need. Here are a few common distributions and their use cases:
std::uniform_int_distribution
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dist(1, 6);
for (int i = 0; i < 5; ++i) {
std::cout << dist(gen) << ' ';
}
}
3 5 2 6 1
std::uniform_real_distribution
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<double> dist(
0.0, 1.0);
for (int i = 0; i < 5; ++i) {
std::cout << dist(gen) << ' ';
}
}
0.278498 0.534335 0.95655 0.157167 0.424719
std::normal_distribution
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<double> dist(
5.0, 2.0);
for (int i = 0; i < 5; ++i) {
std::cout << dist(gen) << ' ';
}
}
6.20473 3.94903 7.31954 1.69591 4.97183
Other distributions like std::exponential_distribution
, std::poisson_distribution
, and std::gamma_distribution
are available for more specific use cases.
Consider the properties of your random number requirements, such as the range, probability distribution, and data type, to select the appropriate distribution.
Answers to questions are automatically generated and may not have been reviewed.
A quick tour of ten useful techniques in C++, covering dates, randomness, attributes and more