比较使用随机数生成的Matlab和Numpy代码 [英] Comparing Matlab and Numpy code that uses random number generation

查看:107
本文介绍了比较使用随机数生成的Matlab和Numpy代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定相同种子的情况下,是否有某种方法可以使numpy中的随机数生成器生成与Matlab中相同的随机数?

Is there some way to make the random number generator in numpy generate the same random numbers as in Matlab, given the same seed?

我在Matlab中尝试了以下方法:

I tried the following in Matlab:

>> rng(1);
>> randn(2, 2)

ans =

    0.9794   -0.5484
   -0.2656   -0.0963

还有在iPython中使用Numpy的以下内容:

And the following in iPython with Numpy:

In [21]: import numpy as np
In [22]: np.random.seed(1)
In [23]: np.random.randn(2, 2)
Out[23]: 
array([[ 1.624, -0.612],
       [-0.528, -1.073]])

两个数组中的值都不同.

Values in both the arrays are different.

或者有人建议比较在Matlab和Python中使用随机数生成的同一算法的两种实现的好主意.

Or could someone suggest a good idea to compare two implementations of the same algorithm in Matlab and Python that uses random number generation.

谢谢!

推荐答案

  1. 确保将相同的数字输入到您的过程中的一种方法是使用两种语言之一生成它们,保存它们并导入另一种语言.这相当容易,您可以将它们写在一个简单的文本文件中.

  1. One way to ensure the same numbers are fed to your process is to generate them in one of the two languges, save them and import into the other language. This is fairly easy, you could write them in a simple textfile.

如果这是不可能或不希望的,您还可以通过自己生成伪随机数来确保数字相同.这是一个显示简单算法示例的网站:

If this is not possible or desirable, you can also make sure the numbers are the same by doing the generation of the pseudo random numbers yourself. Here is a site that shows a very simple example of an easy to implement algorithm: Build your own simple random numbers

如果自制随机生成器的质量不够高,则可以用一种语言构建随机生成函数,然后从另一种语言调用它.最简单的路径可能是从python调用matlab.

If the quality of your homemade random generator is not sufficient, you can build a random generation function in one language, and call it from the other. The easiest path is probably to call matlab from python.

如果您感到幸运,请尝试使用设置.例如,尝试对Matlabs随机函数使用(过时的)seed输入.或尝试使用不同种类的发电机.我相信这两种语言的默认设置都是mersenne twister,但是如果这种实现方式不相同,那么也许更简单.

If you are feeling lucky, try playing around with the settings. For example try using the (outdated) seed input to matlabs random functions. Or try using different kinds of generators. I believe the default in both languages is mersenne twister, but if this implementation is not the same, perhaps a simpler one is.

这篇关于比较使用随机数生成的Matlab和Numpy代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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