1

To describe what I mean, consider the following dummy example:

import numpy as np1
import numpy as np2

seed1 = 1
seed2 = 2

np1.random.seed(seed1)
np2.random.seed(seed2)

where np1.random.normal(0, 2, 1) returns a value completely regardless of what seed2 was. (Which of course does not work in this example.

Is there anyway to have such functionality where there are two independent random generating objects?

Alejandro
  • 879
  • 11
  • 27
  • 2
    Yes, use np.random.RandomState https://stackoverflow.com/a/22995942/2285236 The example uses 42 as the seed for both examples but you can of course set one of them to 1 and the other to 2. – ayhan Dec 15 '20 at 22:14
  • 3
    Note that numpy.random.RandomState is a legacy class as of NumPy 1.17. That version introduced a new random generator system as well as numpy.random.Generator. See the [NumPy RNG policy](https://github.com/numpy/numpy/blob/master/doc/neps/nep-0019-rng-policy.rst). – Peter O. Dec 15 '20 at 22:51
  • 2
    The newest random number package lets you create multiple independent random number generators. – hpaulj Dec 15 '20 at 22:54

1 Answers1

1

With recent versions, you can make multiple random generators. See the docs.

To illustrate, make 2 with the same seed:

In [5]: r1 =np.random.default_rng(1)
In [6]: r2 =np.random.default_rng(1)

They will generate the same random integers without stepping on each other:

In [8]: r1.integers(0,10,5)
Out[8]: array([4, 5, 7, 9, 0])
In [9]: r2.integers(0,10,5)
Out[9]: array([4, 5, 7, 9, 0])

or several more r1 sequences:

In [10]: r1.integers(0,10,5)
Out[10]: array([1, 8, 9, 2, 3])
In [11]: r1.integers(0,10,5)
Out[11]: array([8, 4, 2, 8, 2])
In [12]: r1.integers(0,10,5)
Out[12]: array([4, 6, 5, 0, 0])

Same as Out[10]

In [13]: r2.integers(0,10,5)
Out[13]: array([1, 8, 9, 2, 3])
hpaulj
  • 221,503
  • 14
  • 230
  • 353