3

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.

1
  • 1
    Well everything is in the documentation. The principle behind np.random.default_rng() is create a Generator object to which you can pass a seed argument at its creation for reproducibility. Once you Generator object is created, you can use it to call pre-defined distributions (gumbel, normal, pareto, poisson...), generate random data or do other operations (all described in the documentation). To sum it up, you first need to create a generator, before being able to use its predefined methods Commented Jul 18 at 0:24

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

1 Comment

This answer looks like it may have been written with AI.
1

np.random.default_rng() :

You get a new generator instance, which you control No unintended bleed into other libraries or functions

np.random.seed():

The global RNG state can be altered — The global RNG state is initialize but then after that functions or libraries that uses it might use(read/write) the RNG state

np.random.default_rng() is a local RNG generator(limited to local scope) while np.random.seed() is a global one that can affect any code that uses the global RNG

It's all about the scope local vs global

global means accessed by all libraries that make use of it while local it will be accessible where it was initialized or if passed onto(eg: functions)

1 Comment

Which one to use depends on your situation but np.random.default_rng() is used most of the time because that way you won't have to worry about your seeds affecting other libs or functions,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.