【问题标题】:Matlab: Generating different random numbers in each parfor loopMatlab:在每个 parfor 循环中生成不同的随机数
【发布时间】:2018-03-13 12:02:27
【问题描述】:

我有以下代码:

nruns=100
nloops=2
zz=zeros(nloops,nruns);

for wLoop=1:nloops
delete(gcp('nocreate'));
parpool(npools);
parfor wRun=1:nruns
zz(wLoop,wRun)=rand
end
end
disp('done')

size(unique(zz))

每次池关闭并重新打开时,种子似乎都会重新初始化为其默认值,因此我得到的不同数字比预期的 nruns*nloops 少得多。 如果我添加

,此行为不会改变
rng('shuffle','combRecursive')

在 parfor 内部或之前。 如果我不在每次迭代时都关闭池,则没有问题,但是在每次迭代中使用不同的池对于我所考虑的用法是必要的。 如何在 parfor 循环的每次迭代中获得真正不同的随机数?

【问题讨论】:

    标签: matlab random parfor random-seed


    【解决方案1】:

    首先,此处记录了现有行为:https://uk.mathworks.com/help/distcomp/control-random-number-streams.html。 (请注意,这与 MATLAB 本身基本相同 - 它始终以完全确定性的随机数生成器状态启动 - 尽管 parfor 循环中的迭代实际上并没有确定性地分派)。

    要回答您的问题 - 您可以调整in this doc page 概述的方法。这是一种方法:

    % Shuffle the state at the client
    rng('shuffle');
    % Pick an offset
    streamOffset = randi(10000);
    
    out = zeros(10);
    for idx = 1:10
        parfor jdx = 1:10
            setupRandStream(idx + streamOffset, jdx);
            out(idx, jdx) = rand;
        end
    end
    
    % Set up the global random number state to the specific stream
    % and substream using combined recursive generator.
    function setupRandStream(stream, substream)
    s = RandStream.create('mrg32k3a', 'NumStreams', stream, ...
        'StreamIndices', stream);
    s.Substream = substream;
    RandStream.setGlobalStream(s);
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2019-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多