Alejandro
Alejandro

Reputation: 949

How to have multiple numpy random generating objects with different seeds t the same time

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?

Upvotes: 1

Views: 1105

Answers (1)

hpaulj
hpaulj

Reputation: 231355

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

Upvotes: 2

Related Questions