Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 171 ยท Utilities

Random Numbers

Learn to generate random numbers in modern C++ with <random> - why rand() is bad, mt19937 engines, seeding, uniform and normal distributions, weighted picks and std::shuffle.

Games roll dice, simulations sample measurements, tests generate inputs, and load balancers pick servers. All of them need random numbers. C++ inherited rand() from C, and you'll see it in countless old tutorials and code bases, but it has real problems. Since C++11 the <random> header gives you a far better toolkit that separates where the randomness comes from from what shape the numbers should have.

In this lesson you'll learn why rand() is discouraged, how engines and distributions work together, how to seed properly, how to get reproducible results for tests, how to pick weighted items and shuffle containers, and which mistakes make random code subtly wrong. Everything here is pseudo-random: good for games, simulations and testing, but never for passwords or encryption keys.

Why not rand()?

The classic recipe is srand(time(nullptr)); once, then rand() % 6 + 1 for a die. It has several problems:

  • Small, platform-dependent range. rand() returns 0 to RAND_MAX, which is only guaranteed to be at least 32,767 (and is exactly that on Windows).
  • Modulo bias. % n makes some results more likely unless RAND_MAX + 1 is a multiple of n. The next example shows the effect.
  • Unspecified quality. The algorithm is up to the implementation; some have short cycles and patterns in their low bits.
  • Hidden global state. Every caller shares one generator, it isn't guaranteed to be thread-safe, and any library calling srand resets your sequence.
  • Weak seeding. time(nullptr) changes once per second, so programs started in the same second get the same "random" numbers.

Modulo bias is easy to see with a tiny generator. Pretend a generator produces the values 0 to 7 with equal probability, and we map them to a die with % 6:

C++ Modulo bias, counted exactly

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

With a real RAND_MAX of 32,767 the bias is smaller (faces 1 and 2 win 5,462 of 32,768 outcomes, the others 5,461), but it's still there, and it grows as n grows. For a range of 20,000 values, the first 12,768 numbers would be twice as likely as the rest. The <random> distributions avoid this bias by design.

Engines and distributions

<random> splits the job in two:

  1. An engine produces raw random bits: a stream of unsigned integers with good statistical properties. It holds state and advances each time you call it.
  2. A distribution turns those bits into numbers with the shape you want: "an integer from 1 to 6, all equally likely" or "a double around 170 with standard deviation 8".

You call the distribution and pass it the engine: dist(engine). The usual starting point is:

  • std::mt19937 (the 32-bit Mersenne Twister) or std::mt19937_64 as the engine: fast, high quality for simulation, period of 219937 โˆ’ 1.
  • std::random_device to get a seed: it asks the operating system for unpredictable bits.
C++ Rolling dice the modern way

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Run it a few times: the rolls change, and the histogram bars stay almost equal. Note the boundaries, which trip up many people:

  • uniform_int_distribution{a, b} produces values in the closed range [a, b], both ends included.
  • uniform_real_distribution{a, b} produces values in the half-open range [a, b).

Distributions are cheap objects. Create them where you need them, or keep them next to the engine if you call them often. A distribution may cache bits between calls (the normal distribution produces values in pairs), so call dist.reset() if you ever swap the engine it's used with.

Seeding and reproducibility

An engine's output is completely determined by its seed. That's a feature: with a fixed seed you get the same sequence every run, which is exactly what you want for debugging, unit tests, procedural level generation ("world seed 1234") and scientific reproducibility.

C++ Fixed seeds give repeatable sequences

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Two facts from this example matter in practice:

  • Engines are fully specified; distributions are not. The standard defines the exact algorithm of mt19937, so its raw numbers match on every compiler. But it doesn't say how uniform_int_distribution or normal_distribution turn bits into values, so GCC, Clang's libc++ and MSVC give different dice rolls for the same seed. If your saved games or test fixtures must match across platforms, write your own small mapping from raw engine output (or use a library that pins one).
  • Copies duplicate the stream. Passing an engine to a function by value creates a copy, and the caller's engine never advances, so the same "random" numbers come out again and again. Always pass engines by reference (std::mt19937& engine).

For unpredictable runs, seed from std::random_device. One rd() call gives 32 bits, which is plenty for games. The Mersenne Twister has 19,937 bits of state, though, and a single 32-bit seed means only about four billion possible sequences. For simulations that run many independent streams, feed more entropy through std::seed_seq:

C++
std::random_device rd;
std::seed_seq seeds{rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()};
std::mt19937_64 engine{seeds};

std::random_device is meant to be non-deterministic, but the standard allows a deterministic fallback when no hardware or OS source exists. Very old MinGW versions on Windows really did return the same sequence every run. rd.entropy() is supposed to report 0 in that case, though some libraries report 0 even when they're fine. On current GCC, Clang and MSVC it reads the operating system's secure random source.

Beyond uniform numbers, <random> has about twenty distributions. These are the ones you'll reach for most:

Distribution Produces Typical use
uniform_int_distribution<T>{a, b} integers in [a, b] dice, random indices
uniform_real_distribution<T>{a, b} reals in [a, b) positions, probabilities
bernoulli_distribution{p} true with probability p "30% chance of rain"
normal_distribution<T>{mean, stddev} bell curve heights, measurement noise
discrete_distribution<int>{weights...} index i with weight w[i] loot tables, weighted choices
poisson_distribution<int>{mean} counts of events arrivals per minute
exponential_distribution<T>{rate} waiting times time between arrivals
binomial_distribution<int>{n, p} successes in n trials coin flips
C++ Normal, Bernoulli and weighted choices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The histogram traces a bell curve centered on 170, and the counts match the weights closely. Because the seed is fixed, the numbers are the same each time you run it on our server. A different standard library would print different counts with the same overall shape, as explained above.

Shuffling, sampling and picking

<algorithm> builds on engines for common jobs:

  • std::shuffle(first, last, engine) (or std::ranges::shuffle(range, engine)) puts the elements in a uniformly random order. The old std::random_shuffle used rand() and was removed in C++17.
  • std::sample(first, last, out, n, engine) copies n distinct elements chosen at random, keeping their original relative order.
  • A random element is v[std::uniform_int_distribution<std::size_t>{0, v.size() - 1}(engine)] (check that v isn't empty first).
C++ Shuffling a deck and drawing samples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The random_engine() helper is a good pattern for applications: one engine per thread (thread_local, see Threads), seeded once, shared by reference. It avoids the three classic mistakes: creating a new engine on every call (slow, and with a weak seed source the numbers repeat), copying engines, and sharing one engine between threads without a lock (a data race, because calling an engine modifies it).

Security: none of this is cryptographic

mt19937 is predictable: after observing 624 consecutive outputs, an attacker can reconstruct its state and predict everything that follows. Never use it (or rand()) for passwords, session tokens, password-reset links, encryption keys or anything an attacker benefits from guessing.

For those, use your operating system's cryptographic generator through a library: getrandom() on Linux, BCryptGenRandom on Windows, or a library such as libsodium (randombytes_buf) or OpenSSL (RAND_bytes). std::random_device usually reads from the OS secure source on mainstream platforms, but the standard doesn't promise it, so security code shouldn't rely on it.

Common mistakes

  • Re-creating the engine inside a loop or function, especially as std::mt19937 e{std::time(nullptr)};. Every call in the same second gets the same number. Create the engine once.
  • Passing engines by value. The copy's numbers repeat the original's. Pass Engine&.
  • Writing dist(engine) with rand()-style off-by-one. uniform_int_distribution{0, n} includes n; for an index use {0, n - 1}.
  • Expecting identical results across compilers from distributions. Only engines are portable.
  • Using std::default_random_engine. Its algorithm is implementation-defined (it's minstd_rand0 on GCC, a weak choice). Name the engine you want.
  • Sharing an engine across threads without synchronization. Use one per thread.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What values can std::uniform_int_distribution<int> d{1, 6}; produce?

    The integer distribution uses a closed range [a, b]. The real-number distribution uses a half-open range [a, b) instead.
  2. 2. A function is declared int roll(std::mt19937 engine) and called three times with the same engine. What happens?

    Passing by value copies the engine's state. The caller's engine never advances, so every call starts from the same state. Take std::mt19937& instead.
  3. 3. You seed std::mt19937 with 42 on GCC and on MSVC and roll a uniform_int_distribution die. Will the rolls match?

    mt19937 produces identical raw numbers everywhere, but each standard library maps them to distribution values in its own way.
  4. 4. Why is rand() % 6 biased?

    The leftover values at the top of the range wrap around to the smallest remainders, making them slightly more likely. Distributions in <random> avoid this.
  5. 5. Which is appropriate for generating a password-reset token?

    Mersenne Twister output can be predicted after enough observations, and rand() is worse. Security tokens need a cryptographically secure generator.

Summary

  • Avoid rand(): small range, modulo bias, unspecified quality, hidden global state.
  • Combine an engine (std::mt19937, std::mt19937_64) with a distribution (uniform_int_distribution, normal_distribution, discrete_distribution, ...): dist(engine).
  • Seed once from std::random_device (or a std::seed_seq of several values); use a fixed seed for reproducible tests.
  • Engine output is portable; distribution output differs between standard libraries.
  • Pass engines by reference, keep one per thread, and use std::ranges::shuffle and std::ranges::sample for shuffling and sampling.
  • Nothing in <random> is suitable for security; use a cryptographic generator for tokens and keys.

Next: Regular Expressions, where you'll match, search and replace text patterns with std::regex.