Direct way to access Numpy RandomState object

323 Views Asked by At

Is there are more direct way to access the RandomState object created on import other than np.random.<some function>.__self__? Both np.random._rand and getattr(np.random, "_rand") raise AttributeError. The former works fine but doesn't seem very transparent/Pythonic, though the most transparent might just be creating a separate RandomState object. The purpose is passing the interal_state variable to a cython function that calls randomkit functions directly.

2

There are 2 best solutions below

6
On BEST ANSWER

You can use np.random.get_state() to access the random state and np.random.set_state() to set it.

Example usage:

>>> import numpy as np
>>> state = np.random.get_state()
>>> np.random.rand()
0.5951085367670415
>>> np.random.set_state(state)
>>> np.random.rand()
0.5951085367670415

Note that state is just a tuple

>>> state
('MT19937', array([3133054952,  999208925, 1226199620, ..., 3991712371,  943990344,
    955790602], dtype=uint32), 624, 0, 0.0)
0
On

Found an answer thanks to kazemakase: _rand is accessible directly, I'd just need to import mtrand. But __self__ may be more future proof, if syntax doesn't change.