Sub topic 14
Random arrays with default_rng
This chapter assumes you can create arrays, read their shape and dtype, and pass a size argument as a shape tuple. Random arrays are useful for test data, simulations, sampling, and shuffling. NumPy's current interface for them is the Generator object.
Creating a Generator
Call np.random.default_rng once and keep the result. The optional argument is a seed. The same seed always produces the same stream of numbers.
import numpy as np
rng = np.random.default_rng(42)
ints = rng.integers(0, 10, size=3)
samples = rng.normal(loc=0.0, scale=1.0, size=(2, 2))
print(ints.shape, samples.shape) # (3,) (2, 2)Every generator method takes a size argument. It accepts an integer or a shape tuple, so the result follows the same shape rules as np.zeros.
Reproducibility
Two generators built from the same seed give identical results. Without a seed, NumPy draws fresh entropy from the operating system, so each run differs.
import numpy as np
a = np.random.default_rng(7).random(3)
b = np.random.default_rng(7).random(3)
print(np.array_equal(a, b)) # TrueReproducibility holds for the same sequence of calls. If you draw an extra number before the call you care about, every later result changes.
Common methods
| Method | Returns |
|---|---|
| `rng.random(size)` | floats in the half-open range [0, 1) |
| `rng.integers(low, high, size)` | integers from `low` up to, but not including, `high` |
| `rng.normal(loc, scale, size)` | samples from a normal distribution |
| `rng.choice(a, size, replace)` | elements sampled from an array or from `range(a)` |
| `rng.shuffle(x)` | nothing; reorders `x` in place |
| `rng.permutation(x)` | a shuffled copy |
import numpy as np
rng = np.random.default_rng(0)
picked = rng.choice(5, size=3, replace=False) # 3 distinct values from 0..4
print(picked.shape) # (3,)
x = np.arange(5)
rng.shuffle(x) # modifies x itself
print(sorted(x.tolist())) # [0, 1, 2, 3, 4]
die = rng.integers(1, 7, size=4) # high is exclusive, so 1..6
print(die.min() >= 1 and die.max() <= 6) # TrueCommon errors
- Off-by-one on
integers. The upper bound is exclusive. For a die, userng.integers(1, 7), or passendpoint=Trueto include the upper bound. - Re-creating the generator in a loop.
np.random.default_rng(1)inside a loop returns the same numbers every iteration. Create it once, outside the loop. - Expecting
shuffleto return a value. It returnsNoneand changes the array. Usepermutationwhen you need to keep the original. - Mixing old and new APIs.
np.random.seedandnp.random.randuse a legacy global state. They do not affect aGenerator, and the reverse is also true.
Exercise
What is wrong with this code, and how do you fix it? for i in range(3): print(np.random.default_rng(5).integers(0, 100))
Show answer
It builds a new generator with the same seed on every iteration, so it prints the same number three times. Create rng = np.random.default_rng(5) before the loop and call rng.integers(0, 100) inside it.
Exercise
Write one expression that makes a 3x4 array of random integers from 1 to 6 inclusive, using a generator named rng.
Show answer
rng.integers(1, 7, size=(3, 4)), or equivalently rng.integers(1, 6, size=(3, 4), endpoint=True).