In C++, the modern way to generate random numbers is to use the <random> header, which provides std::mt19937 (a Mersenne Twister engine) and distribution classes like std::uniform_int_distribution. A simple example: std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dist(1, 100); int random_number = dist(gen); This replaces the older, less reliable rand() and srand() functions from C.
Why the Old rand() Is Discouraged
For decades, C++ programmers used rand() from <cstdlib>. It’s simple: call srand(time(0)) once, then rand() returns a pseudo-random integer between 0 and RAND_MAX (often 32767). However, rand() has known problems:
- Poor distribution: The low-order bits are notoriously non-random; using
rand() % nintroduces modulo bias unlessndividesRAND_MAXexactly. - Implementation-defined quality: The algorithm varies across compilers and platforms, so your program’s behavior isn’t portable.
- No easy way to get different distributions: You have to manually transform the integer output to get a normal, Poisson, or other distribution.
The C++11 standard introduced <random> to address these issues, and it is now the recommended approach for all new code.
Core Components of <random>
The <random> library separates two concerns: generating raw random bits (the engine) and shaping those bits into a desired distribution (the distribution).
- Engines: Produce a sequence of unsigned integers. Common engines include
std::mt19937(Mersenne Twister, fast and good quality),std::mt19937_64(64-bit version),std::minstd_rand(small and fast, but lower quality), andstd::random_device(a non-deterministic source, if available). - Distributions: Transform engine output into a specific statistical distribution. Examples:
std::uniform_int_distribution<int>,std::uniform_real_distribution<double>,std::normal_distribution<double>,std::bernoulli_distribution.
You always combine an engine with a distribution. The engine is seeded (initialized) with a starting value, and the distribution object is called with the engine as an argument.
Step-by-Step: Generating a Random Integer
Here’s a complete, correct example that generates a random integer between 1 and 100 (inclusive):
#include <iostream>
#include <random>
int main() {
// Seed with a true random number from random_device
std::random_device rd;
// Mersenne Twister engine seeded with rd()
std::mt19937 gen(rd());
// Uniform distribution from 1 to 100
std::uniform_int_distribution<int> dist(1, 100);
// Generate and print a random number
int random_number = dist(gen);
std::cout << random_number << std::endl;
return 0;
}
This code works on any C++11 or later compiler. The std::random_device is used to seed the engine with a non-deterministic value (if supported), which is better than using time(0) because it avoids predictable sequences.
How to Choose an Engine and Seed
Selecting the right engine depends on your needs:
- General-purpose:
std::mt19937is the default choice. It’s fast, has a long period (2^19937 – 1), and passes many statistical tests. - Cryptographic security: None of the standard engines are cryptographically secure. For security-sensitive applications (passwords, tokens), use
std::random_devicedirectly if it’s non-deterministic, or use a dedicated library like OpenSSL’s RAND_bytes. Never usemt19937for cryptography. - Reproducibility: If you need the same sequence every run (e.g., for testing), seed with a fixed constant:
std::mt19937 gen(42);. - Seeding with random_device:
std::random_devicemay be implemented as a pseudo-random generator on some platforms (e.g., some older MinGW versions), so it’s not guaranteed to be truly random. Still, it’s the best portable seed source.
A common pitfall is re-seeding the engine every time you need a random number. That can lead to repeated sequences if you seed with time(0) and call it quickly. Instead, create the engine once and reuse it.
Generating Different Types of Random Numbers
You can easily get other distributions:
- Real numbers between 0 and 1:
std::uniform_real_distribution<double> dist(0.0, 1.0); - Random boolean:
std::bernoulli_distribution dist(0.5);(50% true) - Normal distribution:
std::normal_distribution<double> dist(mean, stddev); - Random element from a vector: Use
std::uniform_int_distribution<size_t> dist(0, vec.size() - 1);then index withvec[dist(gen)].
For a random double in a range [a, b), you can also use std::uniform_real_distribution. Note that the upper bound is exclusive for real distributions, but inclusive for integer distributions.
Common Problems and Misconceptions
Several pitfalls trip up even experienced programmers:
- Modulo bias: Using
rand() % nis biased because the range ofrand()is not divisible byn. The<random>distributions handle this correctly. - Seeding with time(0) and calling rand() in a loop: If you call
srand(time(0))before eachrand()in a fast loop, you’ll get the same number repeatedly because time doesn’t change that fast. - Using random_device for everything:
std::random_devicecan be slow and may block if the system entropy pool is exhausted. Use it only for seeding. - Thread safety: Engines are not thread-safe. If multiple threads need random numbers, give each thread its own engine, seeded differently (e.g., with
std::random_deviceplus a thread id). - Distribution objects are stateful: Some distributions (like normal) may cache values; reusing the same distribution object across threads can cause data races. Create a separate distribution per thread.
A frequent question: “Can I use rand() for a game?” Yes, if you don’t need high quality or security, but using <random> is just as easy and more reliable.
Performance and Alternatives
std::mt19937 is fast enough for most applications—generating millions of numbers per second. However, if you need even faster generation or a smaller memory footprint, consider std::minstd_rand (a linear congruential generator) or std::ranlux48 (a subtract-with-carry engine). For cryptographic randomness, use platform-specific APIs like BCryptGenRandom on Windows or /dev/urandom on Linux, or a library like OpenSSL.
Another alternative is the std::generate_canonical function, which produces a floating-point number in [0,1) from an engine, but it’s rarely needed because uniform_real_distribution does that.
Frequently Asked Questions
How do I generate a random number between 1 and 6 (like a die)?
Use std::uniform_int_distribution<int> dist(1, 6); and call dist(gen). This gives each number an equal probability, unlike rand() % 6 + 1 which is slightly biased.
What is the difference between rand() and mt19937?
rand() is a simple C function with implementation-defined quality and often poor distribution. std::mt19937 is a Mersenne Twister engine with a much longer period and better statistical properties, and it’s part of C++11’s <random> library.
Can I use time(0) to seed mt19937?
Yes, but it’s not ideal because if you seed multiple engines within the same second, they produce identical sequences. Using std::random_device is better because it provides a non-deterministic seed.
Is std::random_device truly random?
It depends on the implementation. On most modern systems (Linux, Windows, macOS), it accesses a hardware entropy source and is non-deterministic. But on some older or minimal implementations, it may be a pseudo-random generator. Always treat it as a seed source, not as a cryptographic RNG.
How do I generate a random double between 0 and 1?
Use std::uniform_real_distribution<double> dist(0.0, 1.0); and call dist(gen). This gives a value in [0,1) with uniform probability.
Can I use random numbers in multithreaded programs?
Yes, but each thread should have its own engine and distribution objects to avoid data races. Seed each engine differently, for example by combining std::random_device with a thread-specific value like std::hash<std::thread::id>.
Related
- Generating Random Numbers in Python: A Complete Guide
- Python String z Order: Sorting and Comparison
- T-SQL Random Number: RAND, NEWID, and How to Use Them
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Superscript in Excel: Quick Key and Formatting StepsExcel has no single-key shortcut that directly applies superscript. In Excel for Microsoft 365 on Windows, select the…
- How to Open the Visual Basic Editor in ExcelIn Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor (VBE), or choose…
- Google Sheets Conditional Formatting for Data TablesYes. In Google Sheets, you can apply conditional formatting to cells in a table by selecting its range…
- Forgot Excel Sheet Password? Safe Recovery OptionsIf you forgot the password for a protected Excel worksheet, Excel has no built-in command to reveal or…
- Number Rows in Excel When FilteredTo number only the rows currently visible after filtering, put a SUBTOTAL formula in your numbering column and…
- How to Highlight Duplicates in Excel Online: A Quick GuideTo highlight duplicates in Excel Online, select the cells to check, then choose Home > Conditional Formatting >…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.