How does a random number generator work?
download.fan · Updated
Short answer
A random number generator produces numbers in one of two ways. A pseudorandom generator (PRNG) runs a formula from a starting value called a seed, which is fast but repeatable if you know the seed. A true random generator (TRNG) measures a physical process, such as atmospheric noise. Passwords and other security uses need a cryptographically secure generator.
What is the difference between pseudorandom and true random?
- Pseudorandom: calculated by an algorithm. Very fast, and the same seed gives the same sequence. It's fine for games and simulations.
- True random: measured from physical events. Unpredictable, but slower to produce. It suits draws where people want to trust the result.
- Cryptographically secure: designed so results can't be predicted, even by someone who's seen earlier output. It's what passwords and keys need.
Are computer random numbers really random?
Most aren't truly random, though they're very good at looking it. RANDOM.ORG explains the difference, and generates its own numbers from atmospheric noise. For everyday picks, a good pseudorandom generator is effectively as fair as rolling dice.
Not every generator suits every job. MDN warns that JavaScript's Math.random() isn't cryptographically secure and shouldn't be used for security, and points to the Web Crypto API instead.
How does a generator pick a number in a range?
It starts with a raw random value and scales it to your range. A common formula is min + floor(random × (max − min + 1)), where random is a decimal from 0 up to, but not including, 1. For a range of 1 to 100, that gives 100 equally likely outcomes, including both 1 and 100.
You can try it with this random number generator. It draws one whole number between two limits, and its longer form produces many numbers at once, with sorting, decimals and no repeats.
Can a random number generator be predicted?
A pseudorandom one can, if someone knows the algorithm and seed. That's useful in science, as an experiment can be repeated exactly, but it's dangerous in security. Cryptographic generators are built to resist that.