Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct way to access Numpy RandomState object

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.

like image 280
deasmhumnha Avatar asked May 18 '26 21:05

deasmhumnha


1 Answers

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)
like image 157
Jonas Adler Avatar answered May 20 '26 12:05

Jonas Adler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!