NumPy random seed produces different random numbers
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC I Beethoven Sonata No 31 in A Flat M
--
Chapters
00:00 Question
00:52 Accepted answer (Score 10)
01:55 Answer 2 (Score 7)
02:30 Thank you
--
Full question
https://stackoverflow.com/questions/2932...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy #random
#avk47
--
Track title: CC I Beethoven Sonata No 31 in A Flat M
--
Chapters
00:00 Question
00:52 Accepted answer (Score 10)
01:55 Answer 2 (Score 7)
02:30 Thank you
--
Full question
https://stackoverflow.com/questions/2932...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #numpy #random
#avk47
ACCEPTED ANSWER
Score 10
You're confusing RandomState with seed. Your first line constructs an object which you can then use as your random source. For example, we make
>>> rnd = np.random.RandomState(3)
>>> rnd
<mtrand.RandomState object at 0xb17e18cc>
and then
>>> rnd.choice(range(20), (5,))
array([10, 3, 8, 0, 19])
>>> rnd.choice(range(20), (5,))
array([10, 11, 9, 10, 6])
>>> rnd = np.random.RandomState(3)
>>> rnd.choice(range(20), (5,))
array([10, 3, 8, 0, 19])
>>> rnd.choice(range(20), (5,))
array([10, 11, 9, 10, 6])
[I don't understand why your idx1 and idx1S agree-- but you didn't actually post a self-contained transcript, so I suspect user error.]
If you want to affect the global state, use seed:
>>> np.random.seed(3)
>>> np.random.choice(range(20),(5,))
array([10, 3, 8, 0, 19])
>>> np.random.choice(range(20),(5,))
array([10, 11, 9, 10, 6])
>>> np.random.seed(3)
>>> np.random.choice(range(20),(5,))
array([10, 3, 8, 0, 19])
>>> np.random.choice(range(20),(5,))
array([10, 11, 9, 10, 6])
Using a specific RandomState object may seem less convenient at first, but it makes a lot of things easier when you want different entropy streams you can tune.
ANSWER 2
Score 7
I think you should use RandomState class as follows:
In [21]: r=np.random.RandomState(3)
In [22]: r.choice(range(20),(5,))
Out[22]: array([10, 3, 8, 0, 19])
In [23]: r.choice(range(20),(5,))
Out[23]: array([10, 11, 9, 10, 6])
In [24]: r=np.random.RandomState(3)
In [25]: r.choice(range(20),(5,))
Out[25]: array([10, 3, 8, 0, 19])
In [26]: r.choice(range(20),(5,))
Out[26]: array([10, 11, 9, 10, 6])
Basicly, you make an instance r of the RandomState and use it further. As can be seen, re-siding produces the same results.