In C++, the modern way to generate random numbers is to use the <random> header, which provides the std::mt19937 engine and std::uniform_int_distribution for high-quality, flexible random values. For example, std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dist(1, 6); int die = dist(gen); gives a fair die roll. This replaces the older C-style rand() and srand() functions, which are still available but have known limitations.
Background: Why rand() Is Outdated
The C standard library’s rand() function has been around for decades. It returns a pseudo-random integer between 0 and RAND_MAX (often 32767). To use it, you seed the generator with srand(), typically with the current time: srand(time(0)). While this works for simple games or examples, it has several weaknesses:
- Low quality: The underlying algorithm (often a linear congruential generator) has poor statistical properties and can exhibit patterns.
- Limited range:
RAND_MAXis implementation-defined and often small, making it hard to get large random integers. - Modulo bias: Using
rand() % nintroduces bias ifndoesn’t divideRAND_MAX+1evenly. - Global state: The seed is global, so multiple threads need synchronization, and you can’t have independent streams.
Since C++11, the standard library includes a more robust random number facility in <random> that addresses these issues.
How the Modern C++ Random Library Works
The <random> header provides three main components:
- Engines: These are pseudo-random number generators that produce a sequence of unsigned integers. The most popular is
std::mt19937, which implements the Mersenne Twister algorithm. It has a very long period (2^19937 – 1) and good statistical properties. - Distributions: These transform the engine’s raw output into values with a specific distribution. For example,
std::uniform_int_distribution<int>gives integers in a closed range, andstd::uniform_real_distribution<double>gives floating-point values in a half-open range. - Seeds: An engine must be seeded with an initial value.
std::random_deviceis a non-deterministic source (if available) that is often used to seed the engine. Alternatively, you can use a fixed seed for reproducible results (e.g., for testing).
Here’s a complete example that prints five random integers between 1 and 100:
#include <iostream>
#include <random>
int main() {
std::random_device rd; // obtain a seed
std::mt19937 gen(rd()); // seed the engine
std::uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < 5; ++i) {
std::cout << dist(gen) << '\n';
}
return 0;
}
Each call to dist(gen) produces a new random number. The distribution object is reusable; you only need to create it once.
Choosing the Right Engine and Distribution
For most applications, std::mt19937 is a solid default. It’s fast, has a huge period, and passes many statistical tests. However, there are alternatives:
std::mt19937_64: A 64-bit variant that produces larger integers.std::minstd_rand: A simple, fast linear congruential engine, suitable for non-critical uses.std::ranlux48: A higher-quality but slower engine.
For distributions, you typically choose based on the type of random value you need:
std::uniform_int_distributionfor integers in a range (inclusive).std::uniform_real_distributionfor floating-point numbers in [a, b).std::normal_distributionfor values following a bell curve (e.g., for simulations).std::bernoulli_distributionfor true/false outcomes with a given probability.
Always pick a distribution that matches your needs; don’t try to hack a uniform integer from a real distribution.
Common Pitfalls and How to Avoid Them
Even with the modern library, there are mistakes that can ruin your randomness:
- Re-seeding every call: Creating a new engine and seeding it with
random_deviceeach time you need a number is slow and can produce identical sequences if the seed is the same (e.g., if called in a tight loop with the same time). Instead, create the engine once and reuse it. - Using
rand() % n: As mentioned, this introduces bias. Usestd::uniform_int_distributioninstead. - Ignoring thread safety: Engines are not thread-safe. If multiple threads need random numbers, give each thread its own engine (seeded differently) or use a mutex.
- Seeding with
time(0)alone: If two processes start in the same second, they get the same sequence. Preferstd::random_deviceor combine time with other entropy.
Another subtle issue: std::random_device may be implemented as a pseudo-random generator on some platforms (e.g., older MinGW). If you need cryptographic security, don’t rely on it; use a dedicated library like OpenSSL’s RAND_bytes.
Comparison: rand() vs. <random>
Here’s a quick comparison to help you decide:
- Quality:
<random>offers better statistical properties and more control. - Portability:
<random>is standardized, but the exact algorithm may vary between implementations (thoughmt19937is fixed).rand()is also standard but its algorithm is implementation-defined. - Ease of use:
rand()is simpler for trivial cases, but<random>is not much harder and is more flexible. - Performance:
mt19937is generally fast enough for most uses;rand()might be slightly faster on some platforms, but the difference is negligible for most apps.
In short, for any new code, use <random>. Only use rand() if you’re maintaining legacy code or need a quick throwaway script.
Generating Random Floats and Other Distributions
To get a random double between 0.0 and 1.0, use std::uniform_real_distribution<double> dist(0.0, 1.0);. Note that the upper bound is exclusive, so you’ll never get exactly 1.0. If you need a random double in [0, 1] inclusive, you can use std::generate_canonical or adjust the range.
For a normal distribution (e.g., for adding noise to measurements), use std::normal_distribution<double> dist(mean, stddev);. Here’s an example that generates 10 samples from a normal distribution with mean 0 and standard deviation 1:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<double> dist(0.0, 1.0);
for (int i = 0; i < 10; ++i) {
std::cout << dist(gen) << '\n';
}
return 0;
}
This is useful in simulations, Monte Carlo methods, and machine learning.
Reproducibility and Testing
Sometimes you want the same sequence of random numbers across runs—for example, when debugging or running tests. You can achieve this by seeding the engine with a fixed value:
std::mt19937 gen(42); // fixed seed
This makes your program deterministic. If you need different sequences in different runs, use std::random_device or a combination of time and process ID. For tests, you might want to allow the seed to be passed as a command-line argument.
Remember: a pseudo-random generator is deterministic given its seed. That’s a feature, not a bug—it allows you to reproduce results exactly.
Frequently Asked Questions
Q: How do I generate a random number between 1 and 6 in C++?
Use std::uniform_int_distribution<int> dist(1, 6); with a seeded engine like std::mt19937. Call dist(gen) each time you need a new value.
Q: Why is rand() % 100 considered bad?
Because it introduces modulo bias: some numbers are more likely than others if 100 doesn’t divide RAND_MAX+1 evenly. Also, rand() has poor quality. Use uniform_int_distribution instead.
Q: Can I use std::random_device directly for random numbers?
Yes, but it’s slow and may not be truly random on all platforms. It’s best used only to seed a pseudo-random engine.
Q: How do I get a random boolean with a 30% chance of true?
Use std::bernoulli_distribution dist(0.3); and call dist(gen). It returns true with probability 0.3.
Q: Is std::mt19937 thread-safe?
No. Each thread should have its own engine, seeded independently. You can seed them with different values from std::random_device or with a thread-local counter.
Q: What’s the difference between uniform_int_distribution and uniform_real_distribution?
The integer version includes both endpoints (e.g., 1 to 6 inclusive), while the real version is half-open: [a, b), so it includes the lower bound but excludes the upper bound.
Related
- Web Research Data Entry: How It Works
- Button Cell Batteries 1.5 Volt: What You Need to Know
- Get Enum String Value in C#: 4 Ways
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Count Months Between Dates in Excel: Full and Partial MonthsTo count completed months between two dates in Excel, enter the start date in A2 and the end…
- Excel Solver Add-In Not Showing in Ribbon? FixesIf the Solver button is missing from Excel’s ribbon, first enable the built-in add-in: go to File >…
- Excel Freeze Panes: Keep Rows and Columns While ScrollingYes. In Excel for Microsoft 365 on Windows, select the cell just below the rows and to the…
- DS18DSAL 18V Compact Pro Driver Drill Hitachi ReviewThe DS18DSAL is an 18-volt compact driver drill made by Hitachi (now sold under the HiKOKI brand after…
- Excel Solver Add-In: How It Works and How to Use ItExcel Solver is an optimization add-in that finds values for selected cells to maximize, minimize, or reach a…
- How to Add Page Numbers in Word Starting on Page 4To add page numbers in Word starting on the fourth page, insert a Next Page section break at…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.