在Python,NumPy和R中创建相同的随机数序列 [英] Creating same random number sequence in Python, NumPy and R

查看:257
本文介绍了在Python,NumPy和R中创建相同的随机数序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python,NumPy和R都使用相同的算法(Mersenne Twister)来生成随机数序列.因此,从理论上讲,设置相同的种子应在所有3个中产生相同的随机数序列.情况并非如此.我认为这3种实现使用了不同的参数来导致这种行为.

Python, NumPy and R all use the same algorithm (Mersenne Twister) for generating random number sequences. Thus, theoretically speaking, setting the same seed should result in same random number sequences in all 3. This is not the case. I think the 3 implementations use different parameters causing this behavior.


R
>set.seed(1)
>runif(5)
[1] 0.2655087 0.3721239 0.5728534 0.9082078 0.2016819


Python
In [3]: random.seed(1)

In [4]: [random.random() for x in range(5)]
Out[4]: 
[0.13436424411240122,
 0.8474337369372327,
 0.763774618976614,
 0.2550690257394217,
 0.49543508709194095]

NumPy
In [23]: import numpy as np

In [24]: np.random.seed(1)
In [25]: np.random.rand(5)
Out[25]: 
array([  4.17022005e-01,   7.20324493e-01,   1.14374817e-04,
         3.02332573e-01,   1.46755891e-01])

有没有办法让NumPy和Python实现产生相同的随机数序列?当然,正如一些评论和答案所指出的那样,可以使用rpy.我特别想要的是在Python和NumPy的各个调用中微调参数以获取序列.

Is there some way, where NumPy and Python implementation could produce the same random number sequence? Ofcourse as some comments and answers point out, one could use rpy. What I am specifically looking for is to fine tune the parameters in the respective calls in Python and NumPy to get the sequence.

上下文:关注点来自使用R的EDX课程.在其中一个论坛中,有人问是否可以使用Python,工作人员回答说,某些作业需要设置特定的种子并提交答案.

Context: The concern comes from an EDX course offering in which R is used. In one of the forums, it was asked if Python could be used and the staff replied that some assignments would require setting specific seeds and submitting answers.

相关:

  1. 比较Matlab和Numpy代码使用随机数生成.由此看来,底层的NumPy和Matlab实现是相似的.
  2. python vs octave random generator :这个问题确实来了接近预期的答案.需要对默认状态生成器进行某种包装.
  1. Comparing Matlab and Numpy code that uses random number generation From this it seems that the underlying NumPy and Matlab implementation are similar.
  2. python vs octave random generator: This question does come fairly close to the intended answer. Some sort of wrapper around the default state generator is required.

推荐答案

在Python中使用rpy2调用r,这是一个演示,numpy数组data与R中的x共享内存:

use rpy2 to call r in python, here is a demo, the numpy array data is sharing memory with x in R:

import rpy2.robjects as robjects

data = robjects.r("""
set.seed(1)
x <- runif(5)
""")

print np.array(data)

data[1] = 1.0

print robjects.r["x"]

这篇关于在Python,NumPy和R中创建相同的随机数序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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