MATLAB:如何在parfor中设置随机种子以产生与串行相同的结果? [英] MATLAB: How to set random seed in parfor to produce same results as serial for?

查看:444
本文介绍了MATLAB:如何在parfor中设置随机种子以产生与串行相同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了以下最小示例:

I set up the following minimal example:

rng(0);

randseedoffset = random('unid', 10^5) + 1;

t = cell(10,1);
for i = 1:10
    rng(randseedoffset+i);
    t{i} = random('unid', 1000);
end

disp(t);

这将生成10个随机数并将其存储在t中.它将始终可靠地产生相同的随机数,因为我在for循环中使用rng设置了种子.

This will generate 10 random numbers and store them in t. It will always produce the same random numbers reliably because I set the seed with rng in the for loop.

如果现在将for更改为parfor,则会得到不同的结果! 尽管它们也将始终具有可复制性.

If I now change for to parfor, I get different results! Though they will also always be reproducible.

我想用parfor加速我的代码,并且仍然获得与for相同的随机数.

I want to accelerate my code with parfor and still obtain the same exact same random numbers as with for...

推荐答案

好的,我刚刚找到了原因:

Ok, I just found the reason:

MATLAB支持不同的随机数生成算法. 在当前版本的常规设置中,这是Mersenne Twister. 当您进入parfor循环时,这将更改为他们所谓的组合递归方法".

MATLAB supports different random number genereation algorithms. While in the usual setting of the current version this is the Mersenne Twister. When you go into the parfor loop, this changes to what they call 'Combined Recursive Method'.

可以通过在循环中将类型明确设置为'twister'来解决此问题:

The problem can be fixed by explicitely setting the type to 'twister' in the loop:

parfor i = 1:10
    rng(randseedoffset+i, 'twister');
    t{i} = random('unid', 1000);
end

这篇关于MATLAB:如何在parfor中设置随机种子以产生与串行相同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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