A random number generator produces unpredictable numbers within a given range. Programs use randomness to simulate dice rolls, shuffle cards, generate computer moves, and anywhere else an outcome shouldn’t be predictable.
Creating a Generator#
Most languages require you to create a random number generator before using it.
Random random = new Random();new Random() creates a generator seeded with the current time, which produces a different sequence of numbers each run.
import randomPython’s random module is built in. Import it once at the top of the file.
JavaScript has no setup step — Math.random() is available anywhere.
Getting a Random Integer#
To get a random whole number within a specific range:
Random random = new Random();
int number = random.Next(1, 3);random.Next(min, max) returns a random integer. The minimum is inclusive and the maximum is exclusive — Next(1, 3) returns either 1 or 2, never 3.
import random
number = random.randint(1, 2)random.randint(min, max) returns a random integer. Both the minimum and maximum are inclusive — randint(1, 2) returns either 1 or 2.
let number = Math.floor(Math.random() * 2) + 1;Math.random() returns a float between 0 (inclusive) and 1 (exclusive). Multiply by the range size and use Math.floor() to get a whole number, then shift by the minimum value.
Common Mistakes#
Off-by-one with the upper bound in C#
random.Next(1, 2) only ever returns 1 because the upper bound is exclusive. To get 1 or 2, use random.Next(1, 3). Python’s randint is inclusive on both ends, so this mistake doesn’t apply there.
Creating a new generator inside a loop
Creating new Random() inside a loop can produce the same number repeatedly because each instance is seeded from the system clock, which may not change fast enough between iterations. Create the generator once, outside any loop, and reuse it.
Expecting truly random results Computers generate pseudo-random numbers — sequences that appear random but are determined by a starting seed value. For games this is fine. For security-sensitive applications, a cryptographically secure generator is needed instead.
Forgetting to import in Python
random.randint() will raise a NameError if you forget import random at the top of the file.