<random>
The <random>
header, introduced in C++11, provides a comprehensive set of random number generation facilities. It offers a variety of random number engines and distributions, allowing for more sophisticated and statistically sound random number generation compared to the older rand()
function.
#include <iostream>
#include <random>
int main() {
std::random_device rd; // Used to seed the engine
std::mt19937 gen(rd()); // Mersenne Twister engine
std::uniform_int_distribution<> distrib(1, 6); // Distribution for integers 1 to 6
for (int i = 0; i < 10; ++i) {
std::cout << distrib(gen) << " ";
}
std::cout << std::endl;
return 0;
}
std::random_device
to generate a seedstd::mt19937
) for high-quality random numbers#include <iostream>
#include <random>
#include <iomanip>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> distrib(0.0, 1.0);
std::cout << std::fixed << std::setprecision(6);
for (int i = 0; i < 5; ++i) {
std::cout << distrib(gen) << std::endl;
}
return 0;
}
std::uniform_real_distribution
for continuous uniform distribution#include <iostream>
#include <random>
#include <iomanip>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
// Normal distribution
std::normal_distribution<> normal(0.0, 1.0);
// Poisson distribution
std::poisson_distribution<> poisson(4.0);
std::cout << "Normal Distribution (mean=0, stddev=1):" << std::endl;
for (int i = 0; i < 5; ++i) {
std::cout << std::fixed << std::setprecision(6) << normal(gen) << std::endl;
}
std::cout << "\nPoisson Distribution (mean=4):" << std::endl;
for (int i = 0; i < 5; ++i) {
std::cout << poisson(gen) << std::endl;
}
return 0;
}
<random>
library in handling various statistical distributions#include <iostream>
#include <random>
void generate_sequence(unsigned int seed) {
std::mt19937 gen(seed);
std::uniform_int_distribution<> distrib(1, 100);
std::cout << "Sequence for seed " << seed << ": ";
for (int i = 0; i < 5; ++i) {
std::cout << distrib(gen) << " ";
}
std::cout << std::endl;
}
int main() {
generate_sequence(12345);
generate_sequence(12345); // Same seed, same sequence
generate_sequence(67890); // Different seed, different sequence
return 0;
}
<random>
std::uniform_random_bit_generator
, a concept that describes all random number engines in the standard libraryThe <random>
header in C++ provides a powerful and flexible framework for generating random numbers. It offers significant improvements over the older rand()
function, including better statistical properties, a variety of distributions, and more control over the generation process.
std::random_device
to seed your random number enginestd::mt19937
for high-quality random numbersBy leveraging the <random>
library, C++ developers can implement more sophisticated and statistically sound random number generation in their applications, suitable for simulations, games, and various algorithmic needs.