I recently learned about the downsides of using numpy.random.seed(seed). Some internal file can modify the seed.I read an online article that suggested I use np.random.default_rng(). But I am not sure how that works.
I came across this related SO post but it did not help my understanding.
np.random.seed() sets a global seed for NumPy’s legacy random number generator. This global state can be unintentionally modified elsewhere in your code, leading to unpredictable results.
In contrast, np.random.default_rng() creates a new, independent instance of NumPy’s modern Generator (based on the PCG64 algorithm). Each instance maintains its own state and does not affect or rely on any global seed.
Key difference:
You can’t “reseed” the global RNG with default_rng(), it intentionally avoids global state for better reproducibility and isolation.
To get repeatable results, pass a seed when creating the generator:
rng = np.random.default_rng(42)
value = rng.random()
This is the recommended approach in modern NumPy (version 1.17 or later).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With