Sub topic 14
Random arrays with default_rng
This chapter assumes you can create arrays, read their shape, and use axis in reductions. Those topics come from earlier chapters. Here you will learn how NumPy's random number system is built, which methods produce which kinds of arrays, and how to keep results reproducible.
The working model
NumPy generates random numbers with a Generator object. You create one with np.random.default_rng(). A Generator does not produce numbers itself. It wraps a bit generator, an algorithm that outputs a stream of random bits. The default algorithm is PCG64. The Generator converts those bits into integers, floats, or samples from a distribution.
The seed you pass to default_rng is first expanded by a SeedSequence. That step spreads even small seeds like 1 and 2 into well-separated internal states.
If you pass no seed, NumPy takes entropy from the operating system. Each run then gives different numbers. If you pass an integer, every run gives the same numbers, as long as the NumPy version and the sequence of calls stay the same.
Creating random arrays
Every sampling method takes a size argument. It can be an integer or a shape tuple, and the result has that shape.
import numpy as np
rng = np.random.default_rng(42)
ints = rng.integers(0, 10, size=(2, 3)) # integers in [0, 10)
floats = rng.random(size=4) # floats in [0.0, 1.0)
normal = rng.normal(loc=0.0, scale=1.0, size=(2, 2))
uniform = rng.uniform(low=-1.0, high=1.0, size=3)
print(ints.shape, floats.shape, normal.shape, uniform.shape)
# (2, 3) (4,) (2, 2) (3,)The methods you will use most often are these:
| Method | Returns | Notes |
|---|---|---|
| `rng.integers(low, high, size)` | Integers in `[low, high)` | `rng.integers(5)` means `0` to `4` |
| `rng.random(size)` | Floats in `[0, 1)` | Takes a shape, not separate arguments |
| `rng.uniform(low, high, size)` | Floats in `[low, high)` | Use it to rescale the range |
| `rng.normal(loc, scale, size)` | Gaussian samples | `scale` is the standard deviation |
| `rng.choice(a, size, replace, p)` | Elements drawn from `a` | `replace=True` by default |
| `rng.permutation(x)` | Shuffled copy | `x` can be an int or an array |
| `rng.shuffle(x)` | `None` | Shuffles `x` in place |
Integers and the inclusive end
integers excludes the upper bound, like range. Pass endpoint=True to include it. You can also choose the output dtype.
import numpy as np
rng = np.random.default_rng(0)
dice = rng.integers(1, 6, size=10, endpoint=True) # values 1 to 6
small = rng.integers(0, 256, size=5, dtype=np.uint8)
print(dice.min() >= 1, dice.max() <= 6) # True True
print(small.dtype) # uint8Parameters can be arrays
The distribution parameters broadcast against each other and against size. This gives you one column of samples per distribution, all in a single call.
import numpy as np
rng = np.random.default_rng(1)
x = rng.normal(loc=[0, 10, 100], scale=1, size=(1000, 3))
means = x.mean(axis=0)
print(x.shape) # (1000, 3)
print(np.allclose(means, [0, 10, 100], atol=0.2)) # TrueThe last line checks the result with a tolerance. Sample means land near the true means but are never exact.
Reproducibility
The same seed gives the same stream. The stream also advances as you draw from it, so a second draw from the same generator differs from the first.
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)) # True: same seed, same first draw
rng = np.random.default_rng(7)
first = rng.random(3)
second = rng.random(3)
print(np.array_equal(first, second)) # False: the state moved onTwo consequences follow:
- Results depend on the order of calls. If you add one extra
rng.random()call in the middle of a script, every later number changes. - NumPy does not promise identical streams across versions for
Generator. Treat a seed as reproducible within one environment. Do not treat it as a permanent fingerprint. For tests, assert properties such as shape, range, and statistical closeness. Avoid asserting exact values.
Pass the generator, do not recreate it
Create one generator and pass it into functions. If a function builds default_rng(0) internally, every call returns the same numbers.
import numpy as np
def add_noise(x, rng):
return x + rng.normal(0.0, 0.1, size=x.shape)
rng = np.random.default_rng(123)
x = np.zeros(5)
y1 = add_noise(x, rng)
y2 = add_noise(x, rng)
print(np.array_equal(y1, y2)) # False: independent noise on each callAccepting rng as a parameter also lets callers choose the seed, and it makes functions easy to test.
Recording a seed you did not choose
To run unseeded but still be able to repeat a run later, create a SeedSequence and save its entropy.
import numpy as np
seq = np.random.SeedSequence()
print(seq.entropy) # log this number
rng = np.random.default_rng(seq)
replay = np.random.default_rng(np.random.SeedSequence(seq.entropy))
print(rng.random() == replay.random()) # TrueSampling, shuffling, and permuting
choice samples from an array. By default it samples with replacement, so the same element can appear twice. Pass replace=False for a sample with no repeats, and p for weighted probabilities.
import numpy as np
rng = np.random.default_rng(0)
data = np.arange(10)
pick = rng.choice(data, size=4, replace=False)
print(len(set(pick))) # 4: no repeats
weighted = rng.choice(["a", "b"], size=5, p=[0.9, 0.1])
print(weighted.shape) # (5,)Shuffling has a trap. rng.shuffle(x) changes x and returns None, so y = rng.shuffle(x) leaves y as None. For a shuffled copy, use rng.permutation(x). On a 2-D array, shuffle and permutation reorder only along the first axis, so whole rows move together. To shuffle within each row independently, use permuted with an axis.
import numpy as np
rng = np.random.default_rng(5)
m = np.arange(12).reshape(3, 4)
rows = rng.permutation(m) # rows reordered, each row intact
within = rng.permuted(m, axis=1) # each row shuffled on its own
print(np.array_equal(np.sort(within, axis=1), m)) # TrueParallel work needs independent streams
Giving each worker default_rng(0) makes all workers produce identical numbers. Giving them seeds 0, 1, 2 is better, but a cleaner approach is SeedSequence.spawn, which derives child sequences that are designed not to overlap.
import numpy as np
parent = np.random.SeedSequence(12345)
children = parent.spawn(3)
rngs = [np.random.default_rng(s) for s in children]
draws = [r.random() for r in rngs]
print(len(set(draws))) # 3: three different streamsIn NumPy 1.25 and later, rng.spawn(n) does the same thing directly from a generator.
The legacy API
Older code uses np.random.seed(0) and np.random.rand(3). These calls share one hidden global RandomState. Any library that touches it can change your results, and you cannot hand it to a function. RandomState is frozen for backward compatibility and receives no new features. Use default_rng in new code. When you maintain old code, replace rand(n) with rng.random(n) and randint(a, b) with rng.integers(a, b). Their streams differ, so seeded outputs will change.
Common errors
- Expecting
integers(1, 6)to include 6. Useendpoint=Trueor writeintegers(1, 7). - Writing
rng.random(3, 4). The second positional argument is not a dimension, so passsize=(3, 4). - Using
choicewithoutreplace=Falsewhen you need unique items. Asking for more items than the array holds withreplace=FalseraisesValueError. - Re-seeding inside a loop. This repeats the same numbers on every iteration.
- Comparing sample statistics with
==. Usenp.allclosewith a tolerance.
Exercise
A function sample_batch() contains the line rng = np.random.default_rng(0) and then returns rng.random(3). You call it twice in one script. What do you observe, and how do you fix it so the two batches differ while the script stays reproducible?
Show answer
Both calls return the same three numbers, because each call builds a fresh generator from seed 0. To fix it, create one generator at the top of the script, for example rng = np.random.default_rng(0), and change the function to sample_batch(rng) so it returns rng.random(3). The generator's state advances between calls, so the batches differ, and the script still gives identical output on every run.
Exercise
Using a seeded generator, write code that builds a 4x5 array of integers from 1 to 20 inclusive. Then shuffle each row independently without changing the original array.
Show answer
rng = np.random.default_rng(3), then m = rng.integers(1, 20, size=(4, 5), endpoint=True), then shuffled = rng.permuted(m, axis=1). permuted returns a new array by default, so m is unchanged. Using rng.shuffle(m.T) would also work, but it modifies m in place.