3

How can I set numpy.random.seed(0) on a global scale? It seems I have to reset the seed every time I call a np.random function.

import numpy as np

np.random.seed(0)
print(np.random.randint(0,10,2))
np.random.seed(0)
print(np.random.randint(0,10,2))
print(np.random.randint(0,10,2))

np.random.seed(0)
print(np.random.rand())
np.random.seed(0)
print(np.random.rand())
print(np.random.rand())


[5 0]
[5 0]
[3 3]
0.5488135039273248
0.5488135039273248
0.7151893663724195
13
  • 1
    if you want fixed numbers what is the point in using random? Commented Oct 22, 2020 at 7:39
  • 1
    This may answer your question : stackoverflow.com/a/21494630/14280520 Commented Oct 22, 2020 at 7:44
  • 1
    if you could answer as to why you think that you need to reset it, then we would have a chance to help you Commented Oct 22, 2020 at 7:48
  • 2
    There is almost no conceivable use case for what you're asking for - you are almost certainly making a mistake. Why do you think you need this? Commented Oct 22, 2020 at 7:52
  • 1
    You're taking the wrong approach. The thing you're asking for would break all code that uses NumPy random routines anywhere in your program, including stuff you didn't write and didn't want to affect, and stuff you did write that wasn't related to this part. Rather than trying to set the seed "on a global scale", you should do it locally, by using your own instance of numpy.random.RandomState (or better, numpy.random.Generator in new code). Commented Oct 22, 2020 at 8:06

1 Answer 1

3

That is how seeds actually work. You set a 'seed' value which determines all following generated random numbers. You can think of the seed as a starting point for randomly generated numbers. Every time you set the seed you set a starting point for generating a random sequence.

Every time the code generates a random number, it steps 'forward' from the seed/starting point in a random (but deterministic) way. Setting the seed puts the random number generator in a specific state from which it will follow the same random path every time (due to the is the deterministic character).

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

2 Comments

Your explanation is correct. However, this doesn't answer the question. I would like to avoid to set the seed every time I run a np.random function. I want to set it globally. The question is if this is possible at all?
As others have pointed out, that is a common way to use a seed, but to answer your question no don't know if that is possible. One way to work around is to generate a set of random numbers once at the start of your code, and store them in a variable/list. Then every next time you need them you refer to this list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.