Cpp Libs Random
The `` header in the C++ standard library provides a set of tools for generating random numbers, covering everything from simple uniform distributions to complex discrete distributions, offering a wide range of options for applications that require random numbers. These tools are particularly useful in fields such as simulation, game development, and cryptographic algorithms.
The `` library not only supports the generation of pseudorandom numbers but also offers features like seed control and various probability distributions, allowing developers to flexibly generate random number sequences that meet specific requirements.
The `` library consists of three main components:
1. **Random Number Engines**: The core component for generating pseudorandom numbers, controlling the repeatability and randomness of the generation process.
2. **Random Number Distributions**: Control the type of probability distribution that the generated values follow.
3. **Random Number Adapters**: Allow adjustment of engine behavior, such as adapters like `discard_block`.
In C++, Random Number Generators (RNGs) can be divided into two major categories:
* **Pseudorandom Number Generators**: They use deterministic algorithms to generate sequences that appear random. These sequences are theoretically predictable but are usually random enough for most applications.
* **True Random Number Generators**: They generate random numbers based on physical processes (such as thermal noise or radioactive decay), but the C++ standard library does not directly provide such generators.
### Commonly Used Random Number Engines
| Engine | Description |
| --- | --- |
| `std::default_random_engine` | Default random number engine, implementation depends on the specific compiler. |
| `std::minstd_rand` | Linear congruential engine, producing uniformly distributed pseudorandom number sequences. |
| `std::mt19937` | Mersenne Twister algorithm, suitable for general-purpose random number generation. |
| `std::mt19937_64` | 64-bit version of the Mersenne Twister algorithm. |
| `std::ranlux24_base` | Simplified subtractive feedback engine, used for high-quality generation. |
| `std::knuth_b` | Knuth shuffle random number generator. |
The commonly used engine `std::mt19937` is widely recommended because it generates numbers quickly and with high quality. The generator can also use the `seed()` method to specify a seed, making it easy to generate repeatable pseudorandom sequences.
### Random Number Distribution Types
**1. Uniform Distribution**
| Distribution | Description |
| --- | --- |
| `std::uniform_int_distribution` | Generates uniformly distributed integers within a specified integer range. |
| `std::uniform_real_distribution` | Generates uniformly distributed floating-point numbers within a specified range. |
```cpp
std::mt19937 gen(seed);
std::uniform_int_distribution dist(1, 100); // Generates integers between 1 and 100
int random_int = dist(gen);
**2. Normal Distribution**
| Distribution | Description |
| --- | --- |
| `std::normal_distribution` | Standard normal distribution, symmetric around the mean, often used to simulate natural phenomena. |
| `std::lognormal_distribution` | Log-normal distribution. |
```cpp
std::mt19937 gen(seed);
std::normal_distribution dist(0, 1); // Mean is 0, standard deviation is 1
double random_normal = dist(gen);
**3. Discrete Distribution**
| Distribution | Description |
| --- | --- |
| `std::discrete_distribution` | Generates random numbers that are integers with specific probabilities. |
| `std::bernoulli_distribution` | Bernoulli distribution, generating only `true` or `false`. |
| `std::binomial_distribution` | Binomial distribution. |
```cpp
std::mt19937 gen(seed);
std::discrete_distribution dist({40, 10, 50}); // Probabilities are 40%, 10%, and 50%
int random_discrete = dist(gen);
### Syntax
The basic steps for using the `` library are as follows:
* Include the header file ``.
* Create a random number generator object.
* Use distribution classes to generate random numbers.
## Examples
### Generating Basic Random Numbers
## Example
```cpp
#include
#include
int main() {
// Use a random device to create a random seed
std::random_device rd;
// Initialize the Mersenne Twister random number generator with the random seed
std::mt19937 generator(rd());
// Generate a random number
std::cout << "Random number: " << generator() << std::endl;
return 0;
}
Output:
Random number: 3499211612
**Note:** The generated random number may differ each time the program is run.
### Using Uniform Distribution
## Example
```cpp
#include
#include
int main() {
// Create a random number generator
std::mt19937 generator;
// Create a uniform distribution random number generator with a range from 1 to 10
std::uniform_int_distribution distribution(1, 10);
// Generate and print 5 random numbers
for(int i = 0; i < 5; ++i) {
std::cout << "Random number: " << distribution(generator) << std::endl;
}
return 0;
}
Output:
Random number: 7
Random number: 10
Random number: 6
Random number: 2
Random number: 4
Each time the program is run, the sequence of random numbers may differ.
### Using Normal Distribution
## Example
```cpp
#include
#include
#include
int main() {
// Create a random number generator
std::mt19937 generator;
// Create a normal distribution random number generator with mean 0 and standard deviation 1
std::normal_distribution distribution(0.0, 1.0);
// Set output format to display two decimal places
std::cout << std::fixed << std::setprecision(2);
// Generate and print 5 random numbers
for(int i = 0; i < 5; ++i) {
std::cout << "Random number: " << distribution(generator) << std::endl;
}
return 0;
}
Output:
Random number: -0.15
Random number: 0.13
Random number: -1.87
Random number: 0.46
Random number: -0.21
Using the mt19937 engine to generate random numbers with different distributions:
## Example
```cpp
#include
#include
int main() {
// 1. Set the seed and random number engine
std::random_device rd; // Random device to generate the seed
std::mt19937 gen(rd()); // Mersenne Twister engine
// 2. Uniform integer distribution
std::uniform_int_distribution dist_int(1, 100);
std::cout << "Uniform integer: " << dist_int(gen) << std::endl;
// 3. Uniform real distribution
std::uniform_real_distribution dist_real(0.0, 1.0);
std::cout << "Uniform real: " << dist_real(gen) << std::endl;
// 4. Normal distribution
std::normal_distribution dist_normal(0, 1);
std::cout << "Normal: " << dist_normal(gen) << std::endl;
// 5. Discrete distribution
std::discrete_distribution dist_discrete({10, 20, 70});
std::cout << "Discrete: " << dist_discrete(gen) << std::endl;
return 0;
}
### Random Number Adapters
Random number adapters allow adjustment of the generation behavior. There are two main types of adapters:
1. `std::discard_block_engine`: Discards a certain number of generated values, keeping only values at specified intervals, used to reduce randomness.
2. `std::independent_bits_engine`: Generates random numbers with a specified number of bits, making it convenient to directly generate binary data.
## Example
```cpp
#include
#include
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::discard_block_engine discard_engine(gen);
std::cout << "Discard block random number: " << discard_engine() << std::endl;
return 0;
}
### Common Usage
* **Use seeds to generate repeatable random sequences**: Specifying the same seed ensures that the same sequence is generated each time the program runs.
* **Generate random numbers with different distributions**: Choosing a distribution function that matches the application scenario can better simulate real-world problems.
* **Adjust generator performance**: Using different random engines to balance generation performance and accuracy.
YouTip