NumPy Random Intro
Random numbers power simulations, games, statistics, data sampling and machine learning (shuffling data, initialising model weights). NumPy has a complete random-number toolkit in the numpy.random module.
Is a computer's random number really random?
Not quite. A computer follows instructions, so it can't produce true randomness on its own. What it produces are pseudo-random numbers: a deterministic algorithm generates a sequence that looks random and passes statistical tests, starting from an initial value called the seed.
| True random | Pseudo-random | |
|---|---|---|
| Source | physical noise (keystroke timing, radioactive decay, thermal noise) | an algorithm (NumPy uses PCG64) |
| Repeatable? | No | Yes, with the same seed |
| Use for | cryptography, lotteries | simulations, science, ML, games |
Note: For passwords, tokens or anything security-related, use Python's
secretsmodule, not NumPy. NumPy's generators are fast and statistically excellent, but they are not designed to be unpredictable to an attacker.
Repeatability is a feature: with the same seed, you, your colleague and this website all get exactly the same "random" numbers, so results can be checked. That is why every example in this course passes a seed.
The modern way: a Generator
Since NumPy 1.17 the recommended API is to create a Generator object with np.random.default_rng(seed) and call methods on it:
import numpy as np
rng = np.random.default_rng(42) # seed 42 -> reproducible
print(rng.integers(1, 7)) # one die roll: 1..6 (high is exclusive)
print(rng.integers(1, 7, size=10)) # ten die rolls
print(rng.random()) # one float in [0, 1)
print(rng.random(3)) # three floats1
[5 4 3 3 6 1 5 2 1 4]
0.761139701990353
[0.78606431 0.12811363 0.45038594]
Run the example several times: the output never changes, because the seed is fixed. Change 42 to another number and you get a different, but again repeatable, sequence. Calling default_rng() with no seed draws fresh entropy from the operating system, giving different numbers each run.
Arrays of random numbers
The size argument accepts a shape tuple, so you can fill any array at once:
import numpy as np
rng = np.random.default_rng(7)
print(rng.integers(0, 100, size=(3, 5))) # 3x5 integers in 0..99
print(rng.random((2, 3)).round(3)) # 2x3 floats, rounded for display
print(rng.uniform(10, 20, size=4).round(2)) # floats in [10, 20)[[94 62 68 89 57]
[77 83 22 5 30]
[28 87 91 0 49]]
[[0.797 0.468 0.303]
[0.278 0.255 0.445]]
[15.05 15.53 19.96 17.93]
Picking from a list: choice
rng.choice(seq) picks random elements from a sequence. With size it picks several, and replace=False guarantees no repeats (like dealing cards):
import numpy as np
rng = np.random.default_rng(3)
menu = ["pizza", "sushi", "tacos", "curry", "salad"]
print(rng.choice(menu)) # tonight's dinner
print(rng.choice(menu, size=5)) # a week of lunches, repeats allowed
print(rng.choice(menu, size=3, replace=False))
print(rng.choice(10, size=4, replace=False)) # 4 distinct numbers from 0..9salad
['pizza' 'pizza' 'sushi' 'pizza' 'salad']
['curry' 'pizza' 'tacos']
[2 4 8 3]
The legacy API: np.random.seed
Older tutorials and code bases use module-level functions with a hidden global state. You will meet them often, so recognise them:
import numpy as np
np.random.seed(42) # seed the global generator
print(np.random.randint(1, 7, size=5)) # like rng.integers
print(np.random.rand(3)) # like rng.random(3)
print(np.random.choice(["a", "b", "c"], size=4))[4 5 3 5 5]
[0.15601864 0.15599452 0.05808361]
['a' 'c' 'b' 'a']
| Legacy (global state) | Modern Generator |
|---|---|
np.random.seed(42) |
rng = np.random.default_rng(42) |
np.random.randint(a, b, size) |
rng.integers(a, b, size) |
np.random.rand(3) |
rng.random(3) |
np.random.randn(3) |
rng.standard_normal(3) |
np.random.choice(x) |
rng.choice(x) |
np.random.shuffle(x) |
rng.shuffle(x) |
The two APIs use different algorithms, so the same seed produces different numbers. Prefer the Generator: it is faster, has better statistical properties, and keeping the generator in a variable makes it obvious which code depends on randomness. The legacy functions are kept only for backward compatibility.
Test yourself
Why do the examples in this course always pass a seed?
- Seeds make numbers truly random
- So that the output is reproducible
- Generators fail without one
- Seeds make generation faster
Which values can rng.integers(1, 7) return?
- 0 to 7
- 1 to 7
- 1 to 6
- 0 to 6
How do you pick 3 different items from a list x with a Generator?
- rng.choice(x, 3)
- rng.choice(x, size=3, replace=False)
- rng.integers(x, 3)
- rng.shuffle(x, 3)