Question 9 of 20 Fundamentals Concept
Why should new NumPy code use a Generator from default_rng rather than np.random.seed?
Short answer
A Generator is an explicit object you create, seed and pass around, so each piece of code owns its random stream. np.random.seed sets hidden global state that any imported library can disturb. NumPy recommends Generator for new code because its algorithms are faster and still improving.
Why
The legacy functions such as np.random.rand all draw from one global RandomState. Calling np.random.seed(42) at the top of a script looks reproducible, but any function that also draws from the global stream changes what every later call returns. Adding one bootstrap step in the middle of an analysis can then silently change a permutation test further down.
With rng = np.random.default_rng(seed) the stream is an object. You pass rng into the functions that need randomness, so the dependency is visible and isolated. default_rng currently uses the PCG64 bit generator. For parallel work, NumPy documents spawning child streams from a SeedSequence or from a parent generator, which gives each worker an independent stream.
The same page warns that seeds such as 12345 and 12346 can produce very similar streams, and recommends a 128-bit seed from secrets.randbits for the root. Two limits matter. RandomState is kept for backward compatibility and is not being removed, so old code still runs.
And a seeded Generator is only promised to repeat its stream on the same NumPy build, environment and machine with the same sequence of calls, so record the version too.
A strong answer covers
- Global seed is shared hidden state
- Generator is explicit and passed into functions
- default_rng uses PCG64
- Spawn child streams for parallel workers
- Record the seed and the NumPy version
Common mistakes
- Believing np.random.seed at the top of a notebook isolates every later random call from changes elsewhere in the code
- Giving parallel workers seeds 1, 2, 3 and so on instead of spawning independent streams
The interviewer might ask next
How would you give 50 cluster jobs independent but reproducible random streams?