Random Module in NumPy
Python · NumPy Library
Theory
NumPy generates random numbers through a Generator: rng = np.random.default_rng(42). The number is a seed; the same seed always produces the same sequence, which makes experiments and examples reproducible. rng.integers(1, 7, size=5) rolls five dice (the high value is excluded), rng.random(3) gives floats from 0 to 1, rng.normal(loc=50, scale=10, size=1000) samples a bell curve with mean 50 and standard deviation 10, and rng.uniform(a, b, size) spreads values evenly.
rng.choice(arr, size=3, replace=False) picks items without repeats, and p=[...] sets the probability of each item. rng.shuffle(arr) reorders an array in place, while rng.permutation(arr) returns a shuffled copy. Older code uses np.random.seed(42) and np.random.randint; it still works, but the Generator API is the recommended style.
Why we use it
Data work needs randomness for sampling, shuffling, simulations and creating test data. A seeded generator makes those results repeatable, so you and your readers get the same numbers every run.
When to use it
Use default_rng with a fixed seed in tutorials, tests and experiments; leave the seed out when you want different results each run. Use choice for sampling, normal for simulated measurements and shuffle before splitting data by hand.
How it works
- rng = np.random.default_rng(42)
- Need whole numbers? Yes: rng.integers(low, high, size). No: Choose a float distribution.
- Bell-shaped data? Yes: rng.normal(loc, scale, size). No: rng.random or rng.uniform.
- Sample or reorder with rng.choice / rng.shuffle
- Same seed gives the same results every run
Syntax
rng = np.random.default_rng(seed)
rng.integers(low, high, size)
rng.random(size) rng.normal(loc, scale, size)
rng.choice(a, size, replace=False, p=None)
rng.shuffle(a) rng.permutation(a)Example
rng = np.random.default_rng(42)
print(rng.integers(1, 7, size=5)) # five dice rollsKey points
- Same seed, same numbers: use one for reproducible work
- integers(low, high) excludes high, like range
- choice(..., replace=False) samples without repeats
- shuffle works in place; permutation returns a copy
- default_rng is preferred over the older np.random.seed style