Computers generate random numbers using either hardware-based true random number generators (TRNGs) that measure physical phenomena, or software-based pseudorandom number generators (PRNGs) that use deterministic algorithms with a seed value. Most everyday applications—games, simulations, cryptography—use PRNGs because they are fast and reproducible, while TRNGs are reserved for security-critical uses like encryption key generation.
Why Randomness Is Hard for Computers
Computers are deterministic machines: given the same input and instructions, they always produce the same output. A CPU executes fixed sequences of logical operations, so it cannot spontaneously produce an unpredictable number without an external source of entropy. This is why “random” in computing almost always means one of two things: a carefully engineered physical measurement (true randomness) or a complex algorithm that appears random (pseudorandomness). The distinction matters because a PRNG’s output is fully predictable if you know its internal state, which is a serious weakness for cryptography.
How Pseudorandom Number Generators Work
PRNGs start with a seed—a number that initializes the algorithm. The algorithm then applies mathematical transformations to produce a sequence of numbers that pass statistical tests for uniformity and independence. Common examples include:
- Linear Congruential Generator (LCG): Uses the formula
Xn+1= (a * Xn + c) mod m. It is simple and fast, but not cryptographically secure. - Mersenne Twister: A widely used PRNG in Python, C++, and many languages. It has a long period (2^19937 – 1) and good statistical properties, but its state can be reconstructed from enough output.
- Cryptographically Secure PRNG (CSPRNG): Algorithms like ChaCha20 or AES-CTR are designed so that even if an attacker sees many outputs, they cannot predict the next one without the secret key. Operating systems use these for security.
The seed is critical: if you seed a PRNG with the same value, you get the exact same sequence. That is useful for debugging or replaying simulations, but dangerous if a user can guess the seed.
True Random Number Generators: Using Physics
True random number generators (TRNGs) gather entropy from physical processes that are inherently unpredictable. Common sources include:
- Thermal noise: Random voltage fluctuations in electronic circuits.
- Radioactive decay: The timing of decay events is quantum-random.
- Atmospheric noise: Variations in radio signals, as used by services like random.org.
- User input: Mouse movements, keystroke timings, or disk drive seek times.
Modern CPUs include a hardware RNG (e.g., Intel’s RDSEED instruction) that uses thermal noise to generate seeds for the system’s CSPRNG. The OS then mixes this entropy into a pool that programs can draw from via system calls like getrandom() on Linux or CryptGenRandom on Windows.
How to Generate Random Numbers in Code
In most programming languages, you should use the built-in random module, but be aware of its type. For example:
- Python:
random.random()uses the Mersenne Twister (not secure). For security, usesecrets.randbelow(n)oros.urandom(). - JavaScript:
Math.random()is implementation-dependent but generally not cryptographically secure. Usecrypto.getRandomValues()for security. - C++: The
<random>header offersstd::mt19937(Mersenne Twister) andstd::random_devicefor seeding. - Java:
java.util.Randomis not secure; usejava.security.SecureRandomfor passwords or tokens.
Always check the documentation: if you need unpredictable results (e.g., generating a password reset token), never use a non-cryptographic PRNG.
Common Problems and Misconceptions
A frequent misconception is that Math.random() is “random enough” for everything. It is not—if an attacker can predict the seed or the internal state, they can predict future numbers. Another issue is modulo bias: when you map a random integer to a smaller range using % n, the results are not perfectly uniform unless the range divides evenly. For example, generating numbers from 0 to 9 using rand() % 10 on a system where rand() returns 0–32767 gives a slight bias toward 0–7. The correct approach is rejection sampling or using a dedicated function like random.randint() that handles it internally.
Another problem is poor seeding. Many older programs seeded with the current time in seconds, making the sequence predictable to within a few million possibilities. Modern systems seed from hardware entropy, but if you write your own PRNG, you must seed it from a secure source.
How to Choose the Right Random Number Generator
Your choice depends on the application:
- Games and simulations: Speed and statistical quality matter more than security. The Mersenne Twister is a good default.
- Cryptography, tokens, passwords: Use a CSPRNG provided by the OS or a well-reviewed library (e.g.,
secretsin Python,cryptomodule in Node.js). - Scientific Monte Carlo simulations: Reproducibility is often needed, so use a PRNG with a fixed seed and a long period.
- Lotteries or gambling: Must be cryptographically secure and auditable—use a TRNG or a CSPRNG with a public seed.
If you are unsure, the safe default is to use the operating system’s secure random API, because it is both fast enough for most uses and resistant to prediction.
Costs, Performance, and Practical Trade-offs
PRNGs are extremely fast—millions of numbers per second. TRNGs are slower because they rely on physical measurements, but they are still fast enough for seeding and key generation. The main cost is not speed but entropy availability: if a system has no hardware RNG and runs in a virtual machine with little user input, it may struggle to gather enough entropy to seed securely. In such cases, administrators can use hardware devices or network entropy services. For most applications, the performance difference is negligible; the real cost is in implementation complexity and the risk of using an insecure generator.
Frequently Asked Questions
Can a computer generate a truly random number?
Yes, if it uses a hardware TRNG that measures physical processes like thermal noise or radioactive decay. These are truly random in the sense that they are not deterministic. However, most software relies on PRNGs, which are not truly random but are practically indistinguishable for non-security purposes.
Why does the same seed produce the same random numbers?
Because a PRNG is a deterministic algorithm. The seed is the initial state, and the algorithm always transforms that state in the same way. This is intentional: it allows you to reproduce a sequence for testing or replay. If you need different sequences, you must use a different seed (e.g., from a TRNG).
Is Math.random() safe for generating passwords?
No. Math.random() in JavaScript is not cryptographically secure; its output can be predicted if an attacker knows the internal state. For passwords, tokens, or any security-sensitive data, use crypto.getRandomValues() or a dedicated library.
What is the difference between a random number and a pseudorandom number?
A truly random number comes from a physical process with no deterministic pattern. A pseudorandom number is generated by an algorithm that appears random but is actually deterministic. For most purposes, pseudorandom numbers are sufficient, but they are not unpredictable to someone who knows the algorithm and seed.
How do online random number generators work?
They typically use a combination of a TRNG (like atmospheric noise) to generate a seed, then a CSPRNG to produce the numbers. Services like random.org explicitly use atmospheric noise. Others may simply use a PRNG seeded with the server’s current time, which is less secure.
What is entropy in computing?
Entropy is a measure of unpredictability. In the context of random numbers, it refers to the amount of uncertainty in a source. A TRNG provides high entropy because its output is unpredictable. A PRNG’s entropy is limited to the entropy of its seed—if the seed has 128 bits of entropy, the sequence is only as unpredictable as those 128 bits.
Related
- Free Student Attendance Template Excel: Get One
- 911 Dispatch Data Entry Practice Test: 10 Drills
- SAP Logon 800 Data Entry: What It Means
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Lines Between Text Columns in Word: Add or RemoveIn Microsoft Word for Microsoft 365 on Windows, add a vertical line between text columns by opening Layout…
- Excel: How to Count Text vs. Numbers in a Range CorrectlyWith values in A2:A20, count numeric cells with =COUNT(A2:A20) and count cells whose values are text with =SUMPRODUCT(--ISTEXT(A2:A20)).…
- Google Sheets: Get a Percentage of a NumberTo get a percentage of a number in Google Sheets, multiply the number by the percentage: if A1…
- Protect Sheet vs. Protect Workbook in Excel: Key DifferencesIn Excel, Protect Sheet limits what people can change on a particular worksheet, while Protect Workbook can protect…
- How to Add a New Item to an Excel Dropdown List Step by StepTo add a choice to an Excel dropdown, update the list that supplies its options, then confirm the…
- How to Move Cells in Excel Without Overwriting DataTo move cells in Excel, select the cell or range, press Ctrl+X, select the destination, and press Ctrl+V.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.