Random Number Generator — Free Online Calculator Tool
Generate a random number within any range you set. Perfect for games, contests, raffles, and statistical sampling, with instant unbiased results.
Your Random Number
0
About this calculator
Random Number Generator
Comprehensive Guide to Random Number Generator
The Random Number Generator produces discrete uniform integers, continuous floating-point values, non-repeating lottery randomized selections, and randomized shuffled sequences. In computer science, cryptography, scientific modeling, and statistics, random numbers represent values whose outcomes cannot be predicted before they occur. From statistical Monte Carlo simulations modeling financial market risk and nuclear particle diffusion to conducting fair lottery drawings, shuffling digital card decks via the Fisher-Yates algorithm, and generating cryptographic authentication keys, randomness is the core engine of stochastic computation.
In computational theory, a critical distinction exists between Pseudorandom Number Generators (PRNGs) (deterministic mathematical algorithms seeded by an initial state) and True Random Number Generators (TRNGs) (which extract unpredictable physical entropy from thermal resistor noise, atmospheric radio interference, or quantum mechanics).
How to Use the Random Number Generator
- Set Numerical Boundaries: Specify the Minimum (lower bound) and Maximum (upper bound) integer limits (e.g., $1$ to $100$).
- Specify Quantity: Choose how many random numbers to generate in a single batch.
- Toggle Duplicate Filtering:
- Allow Duplicates: Standard for dice rolls, coin flips, and sampling with replacement.
- Unique Numbers Only (No Duplicates): Standard for lotteries, raffle drawings, and tournament seeding.
- Select Output Sorting: Display numbers Unsorted (original random arrival order), Ascending (lowest to highest), or Descending.
- Inspect Randomness Metrics: Review the batch sum, arithmetic mean, theoretical expected value, and chi-square statistical uniformity.
The Calculator Formulas
Discrete uniform distributions, Linear Congruential Generators, and the Fisher-Yates modern shuffle:
1. Discrete Uniform Integer Formula:
R = Min + floor[ U × (Max - Min + 1) ]
Where:
- U ∈ [0, 1) is a continuous uniform random float
- Min and Max are inclusive integer bounds
2. Probability of Any Single Outcome:
P(X = k) = 1 / (Max - Min + 1)
Expected Mean Value E[X] = (Min + Max) / 2
Theoretical Variance Var(X) = [ (Max - Min + 1)² - 1 ] / 12
3. Linear Congruential Generator (LCG Classical PRNG):
X_{n+1} = (a × X_n + c) mod m
Where:
- X_n = Current random integer state
- a = Multiplier constant
- c = Increment constant
- m = Modulus (often 2³¹ - 1 or 2⁶⁴)
- X₀ = Initial Seed
4. Fisher-Yates Modern Array Shuffle Algorithm (O(n)):
To shuffle an array of n elements:
For i from (n - 1) down to 1:
Pick a random integer j such that 0 ≤ j ≤ i
Swap array[i] with array[j]
5. Chi-Square Goodness-of-Fit Uniformity Test:
χ² = Σ_{k=1}^K [ (O_k - E_k)² / E_k ]
Where O_k is observed count and E_k is theoretical expected count.
Practical Examples
Example 1: Non-Repeating Lottery Drawing (6 of 49)
A state lottery commission needs to draw 6 winning numbers from an urn of 49 balls ($1$ to $49$) without replacement.
Parameters: Min = 1, Max = 49, Quantity = 6, Allow Duplicates = False
Step 1: Population Size:
N = 49 - 1 + 1 = 49 balls.
Step 2: Sequential Non-Repeating Extraction:
- Draw 1: U₁ = 0.285 → 1 + floor(0.285 × 49) = 14
- Draw 2: U₂ = 0.816 → 1 + floor(0.816 × 48) = 40 (excluding 14)
- Draw 3: U₃ = 0.041 → 1 + floor(0.041 × 47) = 2
- Draw 4: U₄ = 0.632 → 1 + floor(0.632 × 46) = 31
- Draw 5: U₅ = 0.448 → 1 + floor(0.448 × 45) = 22
- Draw 6: U₆ = 0.918 → 1 + floor(0.918 × 44) = 45
Unsorted Result: [ 14, 40, 2, 31, 22, 45 ]
Ascending Sorted: [ 2, 14, 22, 31, 40, 45 ]
Combinatorial Odds: 1 in C(49, 6) = 1 in 13,983,816.
Example 2: Simulating Fair Six-Sided Die Rolls (Chi-Square Uniformity)
A quality assurance engineer rolls an electronic virtual die $600\text{ times}$ to verify that the random algorithm is statistically fair.
Total Rolls: N = 600
Possible Faces: K = 6 (Faces 1 through 6)
Expected Frequency per Face: E = 600 / 6 = 100 rolls
Observed Frequencies:
Face 1: 96
Face 2: 104
Face 3: 98
Face 4: 105
Face 5: 95
Face 6: 102
Step 1: Compute (O - E)² / E for Each Face:
Face 1: (96 - 100)² / 100 = 16 / 100 = 0.16
Face 2: (104 - 100)² / 100 = 16 / 100 = 0.16
Face 3: (98 - 100)² / 100 = 4 / 100 = 0.04
Face 4: (105 - 100)² / 100 = 25 / 100 = 0.25
Face 5: (95 - 100)² / 100 = 25 / 100 = 0.25
Face 6: (102 - 100)² / 100 = 4 / 100 = 0.04
Step 2: Sum Chi-Square Statistic:
χ² = 0.16 + 0.16 + 0.04 + 0.25 + 0.25 + 0.04 = 0.90
Critical Value for df = 5 at α = 0.05 is 11.07.
Because χ² = 0.90 << 11.07, the generator is confirmed statistically fair and uniform.
Key Concepts & Essential Terminology
Figure: Pipeline comparison between deterministic pseudo-random generators and physical hardware entropy generators.
Understanding random number generation requires navigating computational and statistical concepts:
- Pseudorandom Number Generator (PRNG): An algorithm that generates a sequence of numbers approximating the properties of random numbers. Given the same initial seed, a PRNG will reproduce the exact same sequence identically.
- True Random Number Generator (TRNG): A hardware device that extracts non-deterministic entropy from physical phenomena such as thermal Johnson-Nyquist noise, photoelectric shot noise, or radioactive decay.
- CSPRNG (Cryptographically Secure PRNG): A specialized PRNG designed such that given any sequence of generated outputs, it is computationally infeasible for an adversary to predict subsequent bits (possessing forward and backward secrecy). Examples include
/dev/urandomin Linux and AES-CTR DRBG. - Modulo Bias: A systematic flaw in naive random integer algorithms where computing
rand() % Nfavors smaller numbers if the PRNG's maximum capacity is not an exact multiple of $N$. - Gambler's Fallacy: The cognitive bias of believing that past random outcomes affect future independent events (e.g., believing that after 10 consecutive "Black" outcomes on a roulette wheel, "Red" is "due").
PRNG Algorithms Comparison Matrix
Different software algorithms serve distinct engineering purposes:
| Algorithm Name | Period Length (Cycles) | Cryptographically Secure? | Speed Benchmark | Primary Practical Application |
|---|---|---|---|---|
| Linear Congruential (LCG) | $2^{31} - 1$ or $2^{64}$ | No (Easily cracked) | Ultra Fast | Legacy C standard library (rand()), retro games |
| Mersenne Twister (MT19937) | $2^{19937} - 1$ | No (State exposed after 624 words) | Fast | Python (random), R, Monte Carlo physics modeling |
| Xorshift128+ / Xoshiro256 | $2^{256} - 1$ | No | Fastest (CPU registers) | WebKit JavaScript engine, game physics engines |
| ChaCha20-CSPRNG | $> 2^{64}$ | Yes (NSA approved) | Very Fast | Modern Linux /dev/urandom, TLS 1.3 encryption |
| AES-256 CTR DRBG | $> 2^{64}$ | Yes (FIPS 140-2 certified) | Hardware accelerated | Banking HSMs, defense and government cryptography |
Common Random Discrete Probability Benchmarks
Standard recreational and lottery random event probabilities:
| Event Description | Total Sample Space ($N$) | Single Event Probability ($P$) | Odds Formulation |
|---|---|---|---|
| Fair Coin Toss | 2 outcomes | $0.5000$ ($50.0%$) | 1 in 2 |
| Standard 6-Sided Die (D6) | 6 outcomes | $0.1667$ ($16.67%$) | 1 in 6 |
| Dungeons & Dragons Die (D20) | 20 outcomes | $0.0500$ ($5.0%$) | 1 in 20 ("Natural 20") |
| Single Card Draw (52-Card Deck) | 52 outcomes | $0.01923$ ($1.92%$) | 1 in 52 |
| Roulette Single Number (American) | 38 pockets ($1-36, 0, 00$) | $0.02632$ ($2.63%$) | 1 in 38 (Payout 35 to 1) |
| UK National Lottery (6 of 59) | $45,057,474$ combinations | $0.000000022$ | 1 in 45,057,474 |
| US Powerball Jackpot | $292,201,338$ combinations | $0.00000000342$ | 1 in 292,201,338 |
How Random Number Generation Works
Generating random numbers combines modular group theory, physical entropy harvesting, and rejection sampling:
1. Eliminating Modulo Bias via Rejection Sampling
A common error in naive code is writing:
int result = rand() % 6; // Intended for a 6-sided die
If rand() generates integers uniformly from $0$ to $2^{31} - 1 = 2,147,483,647$:
Because $2,147,483,648$ is not divisible by $6$ ($2,147,483,648 = 357,913,941 \times 6 + 2$), the numbers $0$ and $1$ have an extra chance of appearing compared to $2, 3, 4,$ and $5$. In large-scale gambling or scientific sampling, this skew introduces measurable bias.
Production random generators implement rejection sampling: discarding numbers in the uneven upper remainder zone ($[2^{31} - (2^{31} \bmod N), 2^{31} - 1]$) and re-drawing until an unbiased number is obtained.
2. The Fisher-Yates Modern Shuffle Proof
To shuffle an array of $n$ elements fairly, every one of the $n!$ possible permutations must have an exact probability of $\frac{1}{n!}$.
Naive shuffles that swap every element $i$ with any random element $j \in [0, n-1]$ generate $n^n$ possible execution paths. Because $n^n$ is almost never divisible by $n!$, some permutations are systematically favored over others. The Fisher-Yates modern algorithm avoids this by restricting the swap range at each step $i$ to $[0, i]$, generating exactly $n \times (n - 1) \times \dots \times 1 = n!$ execution paths, proving absolute fairness.
Common Random Number Mistakes to Avoid
- Using Non-Cryptographic PRNGs for Security: Generating API tokens, passwords, or session cookies using
Math.random()or Python'srandommodule. These algorithms can be completely reverse-engineered after observing just 624 consecutive outputs. - Falling Victim to the Gambler's Fallacy: Expecting a number that hasn't appeared recently to be "due." Independent random events have no memory.
- Seeding with the Current Second in High-Frequency Code: Using
srand(time(NULL))inside a fast loop. If called multiple times within the same second, the seed is identical, producing duplicated sequences. - Neglecting Modulo Bias in Custom Integer Ranges: Using basic modulo division without rejection sampling.
- Failing to Save Seeds in Scientific Research: Running scientific simulations without recording the initial PRNG seed, making experiments impossible to reproduce and peer-review.
Frequently Asked Questions
What is the difference between PRNG and TRNG?
A Pseudorandom Number Generator (PRNG) uses a mathematical formula starting from a seed to create a deterministic sequence that appears random. A True Random Number Generator (TRNG) measures unpredictable physical phenomena (such as electronic thermal noise or atmospheric radio waves) to create non-deterministic randomness.
Why is Math.random() not safe for passwords or encryption?
Math.random() in web browsers uses PRNG algorithms like Xorshift128+ optimized for speed in games and simulations, not security. An attacker observing a few dozen outputs can reconstruct the internal state and predict all future numbers. For security, use crypto.getRandomValues().
What is modulo bias in random number generation?
Modulo bias occurs when a random integer is scaled using the % operator. If the maximum range of the generator is not an exact multiple of the desired range, lower numbers have a slightly higher probability of appearing. High-quality generators discard out-of-range values to ensure true uniformity.
How does the Fisher-Yates algorithm guarantee a fair shuffle?
The Fisher-Yates algorithm iterates backwards through an array, swapping the current element with a randomly selected element from the remaining unshuffled portion. This ensures that every one of the n! possible permutations has an exact, equal probability of 1/n!.
What is the Gambler's Fallacy?
The Gambler's Fallacy is the mistaken belief that independent random events are influenced by past outcomes. For example, if a fair coin lands on Heads five times in a row, the probability of Heads on the sixth flip is still exactly 50%.
Why do scientific simulations need reproducible random seeds?
In Monte Carlo simulations and machine learning, researchers need experiments to be reproducible so other scientists can verify results. By fixing the initial random seed, the PRNG generates the exact same sequence of pseudo-random numbers on any computer.
Conclusion
The Random Number Generator delivers uniform discrete integers, non-repeating lottery selections, Fisher-Yates array shuffles, and chi-square statistical validations. By understanding the distinction between deterministic PRNG algorithms and physical TRNG entropy, researchers, game developers, and statisticians can implement stochastic models with complete mathematical integrity.
Related Calculators
Sources & References
- Matsumoto, M., & Nishimura, T. (1998) - Mersenne Twister: A 623-dimensionally Equidistributed Uniform Pseudorandom Number Generator
- NIST Special Publication 800-90A - Recommendation for Random Number Generation Using Deterministic Random Bit Generators
- Knuth, D. E. - The Art of Computer Programming, Volume 2: Seminumerical Algorithms (Chapter 3: Random Numbers)
Technical & General Calculation Disclaimer
This calculation tool applies standard mathematical, scientific, or engineering formulas. While designed for precision, output values are estimates and should be independently verified for commercial, structural, or safety-critical applications.
Comments
Loading comments…
Related Math Calculators
Explore more tools to continue your analysis
Combinations Calculator
Calculate nCr combinations (order unimportant).
Permutations Calculator
Calculate nPr permutations (order important).
Scientific Calculator
Advanced math operations.
Binary Calculator
Binary addition, subtraction, multiplication, division.
Hex Calculator
Hexadecimal arithmetic operations.
Standard Deviation Calculator
Calculate SD and variance for a dataset.
Percentage Calculator
Calculate percentages, increases, and discounts.
Fraction Calculator
Add, subtract, multiply, and divide fractions.