Random Number Guide
What Is Randomness in Computing?
Randomness in computing means producing values that lack any predictable pattern. Computers are deterministic machines — they follow instructions exactly — so generating true randomness is fundamentally hard. Instead, most programming languages rely on pseudo-random number generators (PRNGs): algorithms that produce sequences which look random but are actually determined by an initial value called a seed.
True randomness requires an external source of entropy, such as hardware noise, radioactive decay, or user input timing. Most everyday applications do not need this level of unpredictability and work fine with PRNGs.
Pseudo-Random vs True Random
| Aspect | Pseudo-Random | True Random |
|---|---|---|
| Source | Mathematical algorithm | Physical entropy |
| Reproducible | Yes, with same seed | No |
| Speed | Fast | Slower |
| Predictability | Predictable if seed known | Unpredictable |
| Use case | Games, simulations, testing | Cryptography, security tokens |
A PRNG always produces the same output for the same seed. This is useful for debugging and reproducible tests, but it means anyone who knows the seed can predict every number in the sequence.
Math.random() vs crypto.getRandomValues()
In JavaScript, the two most common ways to generate random numbers serve very different purposes.
Math.random() returns a floating-point number between 0 (inclusive) and 1 (exclusive). It uses a PRNG internally and is fast, but it is not cryptographically secure. An attacker who observes enough outputs can predict future values.
// Simple PRNG — fast but not secure
const value = Math.random(); // 0.374527...
crypto.getRandomValues() fills a typed array with cryptographically strong random values. It draws from the operating system's entropy pool, making it suitable for security-critical tasks.
// Cryptographically secure
const array = new Uint32Array(1);
crypto.getRandomValues(array);
const secureInt = array[0]; // 0 to 4,294,967,295
Use Math.random() for games, animations, and non-security use cases. Use crypto.getRandomValues() for tokens, passwords, and any value an attacker must not predict.
Integer vs Decimal Generation
Most random number generators produce decimal (floating-point) values between 0 and 1. You often need to convert these into integers within a specific range.
Decimal in a range [min, max):
function randomDecimal(min, max) {
return Math.random() * (max - min) + min;
}
Integer in a range min, max (inclusive):
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
The +1 in the integer formula ensures the upper bound is included. Without it, max would never appear in the output.
Common mistake: Using Math.round() instead of Math.floor() biases the distribution — the endpoints min and max each appear half as often as interior values. Always use Math.floor() for uniform integer generation.
Generating Unique Random Values
Sometimes you need random values that do not repeat within a set. Common approaches include:
- Shuffle and pick: Generate all possible values, shuffle the list, then take what you need. Works well when the range is small.
- Track used values: Keep a set of previously generated values and reject duplicates. Simple but degrades in performance as the pool fills up.
- Cryptographic uniqueness: Use UUID v4 for identifiers that are virtually guaranteed to be unique without coordination.
// Fisher-Yates shuffle for unique picks
function shuffledRange(min, max) {
const arr = Array.from({ length: max - min + 1 }, (_, i) => i + min);
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
Choose the method based on your range size and how many values you need relative to the total pool.
Common Use Cases
| Use Case | Type Needed | Generator |
|---|---|---|
| Lottery picks | Unique integers, no repeats | Shuffle or rejection sampling |
| Statistical sampling | Decimal or integer, uniform distribution | PRNG (Math.random) |
| Game dice/cards | Integer in range, possibly unique | PRNG with shuffle |
| Unit test fixtures | Reproducible random data | Seeded PRNG |
| Security tokens | Unpredictable, unique | CSPRNG (crypto.getRandomValues) |
| A/B test assignment | Integer or boolean | PRNG with deterministic seed |
Each use case has different requirements for speed, uniqueness, and unpredictability. Picking the right generator matters — using Math.random() for a security token is a vulnerability, while using crypto.getRandomValues() for a game animation is unnecessary overhead.
Key Takeaways
- Computers generate pseudo-random numbers from algorithms; true random numbers require physical entropy sources.
Math.random()is fast but predictable — never use it for security-critical values.crypto.getRandomValues()provides cryptographically strong randomness suitable for tokens and passwords.- Use
Math.floor(), notMath.round(), for uniform integer distribution. - For unique values, shuffle-based approaches scale better than rejection sampling when you need a large fraction of the available range.
- Match your generator to your use case: PRNG for speed, CSPRNG for security.
Try It Yourself
Generate random integers, decimals, or unique sequences instantly with our free Random Number Generator — no code required.