I'm using np.random.uniform() to generate a number in a class. Surprisingly, when I run the code, I can't see any expected changes in my results. On the other hand, when I use uniform() from python built-in packages, I see the changes in my results and that's obviously normal.
Are they really the same or is there anything tricky in their implementation?
Thank you in advance!
Create one module, say,
blankpaper.py, with only two lines of codeThen, in your main script, execute
You should be getting exactly the same numbers.
When a module or library sets
np.random.seed(some_number), it is global. Behind thenumpy.random.*functions is an instance of theglobal RandomStategenerator, emphasis on theglobal.It is very likely that something that you are importing is doing the aforementioned.
Change the main script to
and you should be getting new numbers each time.
default_rngis a constructor for the random number class,Generator. As stated in the documentation,In reply to the question, "[a]re you setting a seed first?", you said
Imagine we redefine
blankpaper.pyto contain the linesand suppose your main script is
then you should be getting the same numbers as were obtained from executing the first main script (top of the answer).
In this case, the setting of the seed is hidden in one of the functions in the
blankpapermodule, but the same thing would happen ifblankpaper.foowere a class andblankpaper.foo's__init__()method set the seed.So this setting of the global seed can be quite "hidden".
Note also that the above also applies for the functions in the random module
So when
uniform()from therandommodule was generating different numbers each time for you, it was very likely because you nor some other module set the seed shared by functions from therandommodule.In both
numpyandrandom, if your class or application wants to have it's own state, create an instance ofGeneratorfromnumpyorRandomfromrandom(orSystemRandomfor cryptographically-secure randomness). This will be something you can pass around within your application. It's methods will be the functions in thenumpy.randomorrandommodule, only they will have their own state (unless you explicitly set them to be equal).Finally, I am not claiming that this is exactly what is causing your problem (I had to make a few inferences since I cannot see your code), but this is a very likely reason.
Any questions/concerns please let me know!