How Random Number Generation Works: Is a Computer-Picked Number Really Fair?

How Random Number Generation Works: Is a Computer-Picked Number Really Fair?

When you raffle off door prizes by ticket number or pick who presents first in class, chances are you reach for a phone app or a website that picks a random number. And as soon as the result appears, someone says it: "Is that actually random? I thought computers only do exactly what they are told."

That suspicion is half right. A computer is a calculating machine, so the same input always produces the same output. Most computer-generated random numbers are really calculated numbers that only look random. But depending on how they are made, some are perfectly fine for a fair draw while others can be predicted with little effort. This guide explains how random number generation works in plain language, walks through the common algorithms and the hidden trap called modulo bias, and ends with a practical checklist for deciding whether a draw tool is fair.


1. Three Kinds of Computer Randomness — the Source Decides Fairness

A random number is a value produced without any pattern. Two properties matter. First, every value should be equally likely (uniformity). Second, nobody should be able to guess the next value from the previous ones (unpredictability). Computer randomness falls into three families depending on how well it meets those two conditions.

Type How it is made Predictable? Reproducible? Examples Good for
Pseudorandom (PRNG) A formula applied repeatedly to a seed Yes, if the internal state is known Same seed, same sequence Math.random, Python random Games, simulations, casual shuffles
Cryptographically secure (CSPRNG) OS-collected entropy plus a cryptographic algorithm Not in practice No crypto.getRandomValues, Python secrets Prize draws, passwords, security tokens
True random (TRNG) Measuring physical noise: thermal, atmospheric, radioactive decay No, by physics No Hardware RNG chips, atmospheric-noise services Seeding crypto hardware, lottery machines

For an everyday draw, the column that matters most is predictability. Even if results are evenly spread, a draw is not fair if someone can work out the next number.

2. How a PRNG Works — One Seed Fixes the Entire Sequence

A pseudorandom number generator takes a starting value called a seed and keeps applying a fixed formula. Each output feeds the next calculation, so the same seed always yields the same sequence. That is why typing the same world seed into Minecraft gives you the same terrain. Swap the seed for something that changes, like the current time, and every run looks different.

The oldest and simplest design is the linear congruential generator (LCG):

next = (a × current + c) mod m

To see it in action, take tiny values: a=5, c=3, m=16, seed=7.

Step Calculation Output
1 (5×7+3) mod 16 = 38 mod 16 6
2 (5×6+3) mod 16 = 33 mod 16 1
3 (5×1+3) mod 16 = 8 mod 16 8
4 (5×8+3) mod 16 = 43 mod 16 11
5 (5×11+3) mod 16 = 58 mod 16 10
6 (5×10+3) mod 16 = 53 mod 16 5

It continues 12, 15, 14, 9, 0, 3, 2, 13, 4 and returns to 7 on the sixteenth step. Every number from 0 to 15 appears exactly once, which looks random at a glance. Look closer and odd and even alternate: 7 (odd), 6 (even), 1 (odd), 8 (even). When m is a power of two, the low bits of an LCG cycle much faster than the high bits, and this toy example shows exactly that. Real LCGs use a huge m such as 2³¹ or 2⁶⁴ to stretch the period, but the formula is so simple that a few consecutive outputs are enough to compute what comes next.

3. Three Common Algorithms — LCG, Mersenne Twister and xorshift

There are many random number generation algorithms, but the ones ordinary users run into mostly belong to these three families.

Algorithm Introduced Period Strengths Weaknesses Where you meet it
LCG 1949 Up to m (typically 2³¹ to 2⁶⁴) One-line formula, very fast Patterned low bits, easy to predict Old C rand, simple embedded code
Mersenne Twister (MT19937) 1997 2¹⁹⁹³⁷−1 Effectively endless period, strong statistics 624 consecutive outputs reveal the full state Python random, PHP mt_rand, Excel RAND (2010 and later)
xorshift family 2003 2¹²⁸−1 (xorshift128+) Only shifts and XORs, fast and light Fails some strict statistical tests, predictable Math.random in major browsers

The Mersenne Twister keeps an internal state of 624 32-bit integers. Observe 624 outputs in a row and you can reconstruct that state, then predict every number that follows. This is why the official Python documentation warns against using the random module for security and points to the secrets module instead.

The browser's Math.random is in a similar position. Chrome's V8 engine has used xorshift128+ since 2015. Its output is statistically even, but the internal state is only 128 bits, and attacks that recover it from a handful of outputs are well documented. In other words, the problem with pseudorandom numbers is not that they are uneven. It is that they can be guessed.

4. Secure and True Randomness — Where Unpredictability Comes From

4-1. True randomness: measuring physical noise

A true random number generator gets its numbers by measurement, not calculation. It converts phenomena that physics says cannot be known in advance, such as thermal noise in a circuit, atmospheric radio noise or the timing of radioactive decay, into digits. Cloudflare's famous wall of lava lamps, filmed to seed its randomness, follows the same idea. Physical measurement is slow, though, and the raw readings need correcting so they do not lean one way, which makes it awkward for supplying large volumes of random numbers on demand.

4-2. Cryptographic randomness: true randomness as the seed

So in practice the two approaches are combined. The operating system continuously gathers hard-to-predict values (entropy), such as keystroke timing, disk and network interrupt timing and the CPU's hardware random instruction. It uses that entropy to seed a cryptographic algorithm like ChaCha20, which then produces random numbers quickly. That is a cryptographically secure pseudorandom number generator (CSPRNG). The decisive difference from an ordinary PRNG is that no amount of collected output lets you compute the internal state or the next value.

In a web browser, the difference shows up in the function name.

Item Math.random() crypto.getRandomValues()
Source Engine's built-in PRNG (xorshift128+ and similar) Operating system CSPRNG
Output A float from 0 up to 1 An array of integers (Uint8, Uint32 and so on)
Predictability Can be inferred from several outputs Not feasible in practice
Guidance in the spec Do not use for security Suitable for security and draws
Best for Animations, game effects Draws, passwords, auth tokens

If something real is at stake, like a prize, which function the tool uses is the first thing to check.

5. Modulo Bias — What Happens When You Map Random Bytes to 1–6

Even with a good source, fairness can break at the last step. The classic trap is modulo bias. A generator usually returns integers from a fixed range, such as 0–255 (one byte) or 0 to about 4.29 billion (32 bits). To turn that into a die roll, many people take the remainder after dividing by 6 and add 1. The catch is that 256 is not divisible by 6.

Since 256 = 6 × 42 + 4, remainders 0–3 occur 43 times each and remainders 4–5 occur 42 times each.

Source range Target range More likely values Less likely values Gap
0–255 (1 byte) 1–6 1–4: 16.80% each (43/256) 5–6: 16.41% each (42/256) About 1.02×
0–255 (1 byte) 1–100 1–56: 1.17% each (3/256) 57–100: 0.78% each (2/256) 1.5×
0 to 2³²−1 (32 bits) 1–6 Off by about 1 in 716 million — Negligible

The second row shows why it matters. Use a single random byte to pick a winner among ticket numbers 1–100 and tickets 1–56 win 1.5 times as often as tickets 57–100. A 32-bit source shrinks the bias dramatically, but it never quite reaches zero.

The clean fix is rejection sampling. Use only the part of the source range that is an exact multiple of the target range and redraw whenever a value falls outside it. To get 1–6 from a byte, redraw only when you get 252–255 (252 = 6 × 42). That happens 4 times in 256, about 1.6%, so the speed cost is tiny.

// Uniform integer from 0 up to n-1 (no modulo bias)
function randInt(n) {
  const limit = Math.floor(2 ** 32 / n) * n
  const a = new Uint32Array(1)
  do crypto.getRandomValues(a)
  while (a[0] >= limit)
  return a[0] % n
}

To put several people in order without repeats, feed these uniform integers into a Fisher–Yates shuffle and every ordering becomes equally likely. The popular shortcut of sorting an array with Math.random as the comparator is best avoided, because depending on the sort algorithm some orderings come up more often than others.

6. So Is It Fair Enough for a Draw? A Use-Case Checklist

Not every situation needs cryptographic randomness. Decide based on what is riding on the result.

Use case Level needed What to check
Game effects, visual flair, simulations A PRNG is fine Log the seed if you need to reproduce runs
Friends picking lunch or turn order A PRNG is fine Run it on a screen everyone can see
Class presenters, chore rotas CSPRNG recommended Announce the number range beforehand
Prize and giveaway draws CSPRNG plus bias removal Turn off repeats, record the draw
Passwords and verification codes CSPRNG required Enough length and character types for entropy
Licensed lotteries, official draws Certified physical machines plus witnesses External audits, published procedures

Procedural fairness matters too. The best algorithm in the world means nothing if someone can keep pressing the button until they like the result. These five checks head off most disputes:

  • Is the source cryptographically secure (crypto.getRandomValues, secrets and the like)?
  • Was modulo bias removed when mapping to the target range?
  • Were participant numbers, the range and the number of winners announced before the draw?
  • Was a redraw rule (for absent winners, for example) agreed in advance?
  • Was the draw shared on screen or recorded?

7. Frequently Asked Questions (FAQ)

Q1. Can computers make truly random numbers?

Not by calculation alone, because calculation always maps the same input to the same output. Modern operating systems, however, collect physical uncertainty such as hardware noise and input timing and use it as a seed. Cryptographic randomness built on top of that is, for practical purposes, indistinguishable from true randomness.

Q2. If the same number comes up twice in a row, is the draw rigged?

No. When picking one number from 1–10, the chance of repeating the previous number is 10% every time. A sequence that never repeats and spreads out perfectly evenly would actually be less random. People tend to picture randomness as "nicely mixed," which is why streaks look suspicious.

Q3. What is a random number table, and is it still used?

It is a printed table of random digits. The best known is the RAND Corporation's 1955 book of one million random digits, used for statistical sampling and cryptography. Computer random number generators have taken over that job, but you still see such tables in statistics classes and offline sampling.

Q4. Can I use Excel's RAND function for a prize draw?

For a casual get-together it is fine. Bear in mind that RAND is pseudorandom and recalculates every time the sheet changes, which makes it fiddly to lock in a result. For any draw where people might dispute the winner, it is cleaner to use a tool built on cryptographic randomness with bias removal and to share your screen while drawing.

8. Run a Fair Prize or Presenter Draw with the Random Number Generator

The HandyWeb Random Number Generator follows every fairness check in this guide. It draws numbers with the browser's crypto.getRandomValues and removes modulo bias with rejection sampling, exactly like the code above, so every number in your range is equally likely. Set the range to your participant count, enter the number of winners, turn off repeats, and your ticket raffle is done in one click. Absent participants can simply go in the exclude box.

If each person should pick a card to see who wins, Draw Lots is the easier option. It shuffles cards for 2 to 30 people using the same uniform randomness and a Fisher–Yates shuffle, so every card has the same chance no matter who picks it. To choose 6 unique numbers from 1–45 lotto-style, use the Lotto Number Generator. All three tools run entirely on your device and send nothing to a server. To see how randomness is used in security, read Password Strength Algorithms and Secure Token Standards next.

Recommended Articles

Back to List