Search code examples
pythonnumpycythonnumpy-random

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.


Solution

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