Web Tools

How Random Number Generators Work

Updated 30 Aug 202610 minWeb Tools
A downward flow on the left runs from a seed value of 12345, through an algorithm step described as same input, same output, every time, into a pseudorandom sequence shown as an illustrative list of 42, 7, 91 and 18. On the right, two stacked blocks compare the two kinds of generator. The pseudorandom block reads deterministic underneath, reproducible with the same seed, and good for games, testing and simulation. The secure random block reads built to resist prediction, use for passwords, tokens and keys, and not the same thing as passing statistical tests. A closing band states that random-looking does not mean unpredictable, notes that the same algorithm plus the same seed reproduces the same sequence which is what makes tests and simulations repeatable, warns that squeezing a wide range into a small one can bias the result unless leftover values are rejected and redrawn, and adds that the numbers shown are an illustration only and not a secure source.

Ask a computer for a random number and, most of the time, it does not give you one. It runs an algorithm that produces a number you cannot easily guess and that behaves statistically like a random one. For dice, shuffles and simulations that is exactly what you want. For a password or a session token it is not enough.

Three Different Things Called "Random"

It helps to separate them before anything else.

True physical randomness. The number comes from a physical process that is not predictable in principle or in practice: thermal noise in a circuit, atmospheric noise, photon behaviour, decay timings. Hardware random generators built into modern CPUs and the entropy pools maintained by operating systems draw on sources like these.

Pseudorandom number generators (PRNGs). An algorithm with an internal state. Given a starting value it produces a sequence that passes statistical tests for randomness, but the sequence is fully determined by that starting value. This is what most ordinary random functions in most languages give you.

Cryptographically secure pseudorandom generators (CSPRNGs). Still algorithms, still deterministic underneath, but designed so that seeing a large amount of output does not let an attacker work out what comes next or what came before. Practical examples include ChaCha20-based generators, AES in counter mode, and hash-based designs such as HMAC-DRBG.

The important line is not "random versus not random". It is "random-looking" versus "unpredictable to someone who is trying".

What a Seed Actually Does

A PRNG has four moving parts: a seed that sets the starting state, the state itself, a transition function that advances the state, and an output function that turns state into a number.

Because everything after the seed is deterministic, the same algorithm plus the same seed reproduces the same sequence, in the same order, every time.

That reproducibility is a feature, not a bug. It is why you can:

  • rerun a failing test with the exact random inputs that broke it
  • share a simulation and have a colleague reproduce your figures
  • regenerate a procedurally built game level from a short code
  • run an A/B experiment where the same participant always lands in the same group

Change the seed and you get an unrelated sequence. Reuse a seed by accident, and yesterday's "random" output turns up again today.

Seeds themselves come from somewhere. A clock reading is easy but guessable. A read from the operating system entropy pool is the right choice when the output must be hard to predict. Language APIs differ in what they do by default, so do not assume that two languages, or two versions of the same language, seed the same way or use the same underlying algorithm.

When Pseudorandom Is Perfectly Fine

For most everyday uses nobody gains anything by predicting the output, so a fast PRNG is the correct engineering choice:

  • dice rolls, coin flips and board game mechanics
  • shuffling a playlist or a deck
  • Monte Carlo and other statistical simulations
  • sampling rows from a dataset
  • randomised demo data, placeholder content and UI variation
  • picking a name from a list at a meeting

When It Is Not

For these, a generic PRNG is the wrong tool regardless of how random the output looks:

  • passwords and passphrases
  • authentication tokens, session identifiers and API keys
  • password reset links
  • cryptographic keys, nonces and salts
  • anything where a real prize or real money rides on the outcome

The reason is not statistical quality. A well-built PRNG passes the same tests a secure generator does. The reason is structural: a general-purpose PRNG makes no attempt to hide its internal state, and its state is what determines every future output. A CSPRNG is built specifically so that recovering that state from observed output is computationally infeasible.

In practice this means using the platform's dedicated interface rather than its general random function: the browser's crypto.getRandomValues(), Python's secrets module, Node's crypto.randomBytes(), or the equivalent in your language. Which one is correct depends on your platform and threat model, and security-sensitive systems deserve a review by someone who does that work.

Range Mapping and Modulo Bias

A generator usually hands you a value from a fixed range. Turning that into "a number from 1 to 6" is where a subtle bug lives.

Suppose your source produces one of ten equally likely values, 0 through 9, and you map it with (value mod 6) + 1:

Source value0123456789
Result1234561234

Count them up. Results 1, 2, 3 and 4 each come from two source values. Results 5 and 6 each come from one. So four faces land 2 times in 10, or 20% each, and two faces land 1 time in 10, or 10% each. The generator was perfectly fair; the mapping was not.

The cause is arithmetic, not randomness: 10 does not divide evenly into 6. The leftover 4 values wrap round and give the first four results a second chance. The same thing happens with a 32-bit or 64-bit source, just far less visibly, which is why it goes unnoticed.

Two standard fixes:

Pick a source range that divides evenly. Twelve equally likely values map cleanly onto six results, two source values each.

Reject and redraw. Keep drawing until the value falls inside the largest block that does divide evenly, and discard the rest. With a source of 0 to 9 and six results, accept 0 to 5 and redraw on 6 to 9. Every accepted value is then equally likely. Most modern standard libraries do something along these lines for you; hand-rolled rand() % n typically does not.

Misconceptions Worth Dropping

"That does not look random." Real randomness produces clumps. Over 100 fair coin flips, a run of six or seven heads is unremarkable. A sequence with no streaks at all is the suspicious one.

"The same number twice in a row means it is broken." A fair six-sided die shows the same face twice in a row one time in six. Three in a row happens one time in thirty-six. Independent draws have no memory of what came before.

"It has been red five times, so black is due." Nothing is due. Independent events do not correct themselves.

"A good random source guarantees a fair shuffle." It does not. The algorithm matters as much as the source. Fisher-Yates, walking from the last index downward and swapping each element with a uniformly chosen element at or before it, produces every ordering with equal probability. Sorting a list with a comparator that returns a random answer does not, and the resulting bias depends on the sort implementation.

"Random means secure." These are separate properties. Statistical randomness is about how the output is distributed. Cryptographic security is about whether an adversary can predict it. A generator can have the first and not the second.

"Uniform is the only distribution." Most APIs give you a uniform result by default. Weighted choices, normal distributions and everything else are built on top of that uniform base, usually by dividing the unit interval into weighted chunks or transforming uniform values with a known formula.

Picking Weighted Options

Weighted choice is the workhorse of loot tables, ad rotation and sampling. Four items with weights 10, 20, 30 and 40 sum to 100. Lay them along a line as cumulative thresholds of 10, 30, 60 and 100, draw a uniform value in the range 0 up to 100, and see which segment it lands in. A draw of 67.5 falls above 60 and at or below 100, so the fourth item wins. Segment widths match the weights, so the long-run frequencies do too.

Testing a Generator

You cannot prove a sequence is random. You can only fail to show that it is not. Standard checks look at whether the output behaves the way genuine randomness would:

  • Chi-squared: do the observed counts match the expected distribution?
  • Runs test: are streaks about as long and as frequent as they should be?
  • Spectral test: do consecutive values fall on a lattice rather than filling the space?
  • TestU01, Dieharder and similar batteries: large collections of the above, run together.

Modern general-purpose generators pass these comfortably. Simple linear congruential generators often do not, particularly in higher dimensions. Passing a test battery says nothing about cryptographic security, which is a separate question with separate analysis.

Everyday Uses and the Tools for Them

TaskWhat is needed
Rolling dice for a gameOrdinary PRNG
Flipping a coin to settle somethingOrdinary PRNG
Picking a raffle winner among friendsOrdinary PRNG, freshly seeded
Drawing a random sample from dataGood-quality PRNG, seed recorded so the sample can be reproduced
Monte Carlo simulationFast, high-quality PRNG; record the seed
Generating a passwordCryptographically secure generator
Generating session tokens or keysCryptographically secure generator

BlinkCalc covers the everyday side of that table. The Random Number Generator produces integers across any range you set. The Dice Roller and Coin Flip handle the game and tie-break cases directly, the Random Name Picker draws a winner from a list, and the Probability Calculator works out how likely a result actually was once you have it. For a password, use a tool built for the job, such as the Password Generator, rather than a general random number.

FAQ

Are computer random numbers truly random? Usually not. Most are pseudorandom: a deterministic algorithm expands a seed into a sequence that behaves statistically like randomness. True random numbers come from physical processes, and operating systems mix physical entropy into the generators they expose for security work.

What is a seed in a random number generator? The starting value that sets the generator's internal state. The same algorithm with the same seed produces the same sequence every time, which is what makes tests, simulations and procedurally generated content reproducible.

What is modulo bias? The uneven distribution you get when you squeeze a larger range of values into a smaller one that does not divide into it evenly. Some results end up reachable from more source values than others. Rejecting the leftover values and redrawing removes the bias.

When do I need a cryptographically secure random number generator? Whenever predicting the output would let someone gain something: passwords, tokens, session identifiers, keys, reset links, and any draw with real value attached. Use the platform's dedicated secure interface rather than its general-purpose random function.

Can a fair random generator produce the same number several times in a row? Yes. On a fair six-sided die, two identical rolls in a row happen about one time in six and three in a row about one time in thirty-six. Repeats are evidence of independence, not of a fault.

Does a good random source guarantee a fair shuffle? No. The shuffle algorithm matters too. Fisher-Yates gives every ordering an equal chance; sorting with a random comparator does not.

Final Thoughts

Pseudorandomness is one of the more elegant tricks in computing: a short seed, a well-chosen algorithm, and out comes something no statistical test can separate from chance. It is also one of the easiest things to misuse, because the output looks equally convincing whether or not it is safe. Keep the two questions apart. Ask whether the numbers are well distributed, and then ask, separately, whether it would matter if somebody could work out what comes next.