The C++ standard library provides the std::random
library for random number generation. This library offers various engines and distributions for producing random numbers with different properties.
Table of Contents
Random Number Engines
std::random
includes several engines such as linear_congruential_engine
, mersenne_twister_engine
, subtract_with_carry_engine
, and others. These engines generate a sequence of uniformly-distributed unsigned integers with a specific range and period.
Random Number Distributions
The library also provides distributions including uniform_int_distribution
, uniform_real_distribution
, normal_distribution
, and more. These distributions transform the output of a random number engine into numbers with different statistical properties, such as uniform or normal distribution.
Example Usage
Here is an example of how to use std::random
to generate random numbers:
#include <iostream>
#include <random>
int main() {
// Create a random number engine
std::mt19937 rng(std::random_device{}());
// Create a uniform distribution
std::uniform_real_distribution<double> dist(0.0, 1.0);
// Generate a random number
double random_number = dist(rng);
// Print the random number
std::cout << "Random number: " << random_number << std::endl;
return 0;
}
In this example, we use the Mersenne Twister engine (std::mt19937
) and a uniform real distribution to generate a random number between 0.0 and 1.0.
The std::random_device
is used to obtain a non-deterministic seed for the random number engine.
By using the std::random
library, developers can easily generate random numbers with various distributions for different applications.
References
- [C++ Standard Library -
](https://en.cppreference.com/w/cpp/header/random) - C++ random