python vs八度随机生成器 [英] python vs octave random generator

查看:94
本文介绍了python vs八度随机生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说,是numpy:

More specifically, numpy:

In [24]: a=np.random.RandomState(4)
In [25]: a.rand()
Out[25]: 0.9670298390136767
In [26]: a.get_state()
Out[26]: 
('MT19937',
 array([1248735455, ..., 1532921051], dtype=uint32),
 2,0,0.0)

八度:

octave:17> rand('state',4)
octave:18> rand()
ans =  0.23605
octave:19> rand('seed',4)
octave:20> rand()
ans =  0.12852

Octave声称执行相同的算法(Merenne Twister的周期为2 ^ {19937-1})

Octave claims to perform the same algorithm (Mersenne Twister with a period of 2^{19937-1})

有人知道为什么会有区别吗?

Anybody know why the difference?

推荐答案

很遗憾,Octave中的MT19937生成器不允许您像np.random.RandomState(4)那样使用单个32位整数对其进行初始化.如果使用rand("seed",4),则实际上会切换到Octave先前使用的PRNG的早期版本,该PRNG根本不是MT19937,而是Fortran RANDLIB.

Unfortunately the MT19937 generator in Octave does not allow you to initialise it using a single 32-bit integer as np.random.RandomState(4) does. If you use rand("seed",4) this actually switches to an earlier version of the PRNG used previously in Octave, which PRNG is not MT19937 at all, but rather the Fortran RANDLIB.

在NumPy和Octave中可以得到相同的数字,但是您必须在Octave中绕过随机种子生成算法,并编写自己的函数以从初始的32位整数种子构造状态向量.我不是Octave专家,但是通过Internet搜索Octave/Matlab中的位操作函数和整数类,我能够编写以下粗略的脚本来实现播种:

It is possible to get the same numbers in NumPy and Octave, but you have to hack around the random seed generation algorithm in Octave and write your own function to construct the state vector out of the initial 32-bit integer seed. I am not an Octave guru, but with several Internet searches on bit manipulation functions and integer classes in Octave/Matlab I was able to write the following crude script to implement the seeding:

function state = mtstate(seed)

state = uint32(zeros(625,1));

state(1) = uint32(seed);
for i=1:623,
   tmp = uint64(1812433253)*uint64(bitxor(state(i),bitshift(state(i),-30)))+i;
   state(i+1) = uint32(bitand(tmp,uint64(intmax('uint32'))));
end
state(625) = 1;

像这样使用它:

octave:9> rand('state',mtstate(4));
octave:10> rand(1,5)
ans =

   0.96703   0.54723   0.97268   0.71482   0.69773

仅用于与NumPy进行比较:

Just for comparison with NumPy:

>>> a = numpy.random.RandomState(4)
>>> a.rand(5)
array([ 0.96702984,  0.54723225,  0.97268436,  0.71481599,  0.69772882])

数字(或至少前五个数字)匹配.

The numbers (or at least the first five of them) match.

请注意,由random模块提供的Python中的默认随机数生成器也是MT19937,但是它使用了不同的种子算法,因此random.seed(4)生成了完全不同的状态向量,因此PRN序列为不同.

Note that the default random number generator in Python, provided by the random module, is also MT19937, but it uses a different seeding algorithm, so random.seed(4) produces a completely different state vector and hence the PRN sequence is then different.

这篇关于python vs八度随机生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆