How to access numpy default global random number generator

纵然是瞬间 提交于 2019-12-04 07:29:14

As well as what kazemakase suggests, we can take advantage of the fact that module-level functions like numpy.random.random are really methods of a hidden numpy.random.RandomState by pulling the __self__ directly from one of those methods:

numpy_default_rng = numpy.random.random.__self__

numpy.random imports * from numpy.random.mtrand, which is an extension module written in Cython. The source code shows that the global state is stored in the variable _rand. This variable is not imported into the numpy.random scope but you can get it directly from mtrand.

import numpy as np
from numpy.random.mtrand import _rand as global_randstate

np.random.seed(42)
print(np.random.rand())
# 0.3745401188473625

np.random.RandomState().seed(42)  # Different object, does not influence global state
print(np.random.rand())
# 0.9507143064099162

global_randstate.seed(42)  # this changes the global state
print(np.random.rand())
# 0.3745401188473625

I don't know how to access the global state. However, you can use a RandomState object and pass it along. Random distributions are attached to it, so you call them as methods.

Example:

import numpy as np

def computation(parameter, rs):
    return parameter*np.sum(rs.uniform(size=5)-0.5)

my_state = np.random.RandomState(seed=3)

print(computation(3, my_state))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!