Matlab中并行循环中的不同(伪)随机数

时间:2014-02-06 13:12:48

标签: matlab random parallel-processing parfor

并行循环中询问随机数总是返回相同的伪随机数。我怎么能避免这个?

% workers initialization:
if matlabpool('size') == 0
    matlabpool('open',2);
else
    matlabpool('close');
    matlabpool('open',2);
end

% parallel loop always give the same random numbers...
parfor k = 1:10
    fprintf([num2str(rand(1,1)), ' ']);
end

一种理想的解决方案是按CPU时间或类似时间初始化每个线程中的伪随机数生成器。 rng('shuffle')之类的东西似乎没有帮助......

控制台输出:

Sending a stop signal to all the workers ... stopped.
Starting matlabpool using the 'local' profile ... connected to 2 workers.
0.32457 0.66182 0.63488 0.64968 
0.26459 0.096779 0.50518 0.48662 0.034895 0.85227 

1 个答案:

答案 0 :(得分:3)

这里有各种选项documentation here。这是你可以采取的一种方式。

numWorkers = matlabpool('size');
[streams{1:numWorkers}] = RandStream.create('mrg32k3a', ...
    'Seed', 'shuffle', 'NumStreams', numWorkers);
spmd
    RandStream.setGlobalStream(streams{labindex});
end

或者,为避免在客户端创建所有流,您可以改为:

rng('shuffle'); % shuffle the client
workerSeed = randi([0, 2^32-1]);
spmd
    stream = RandStream.create('mrg32k3a', ...
        'Seed', workerSeed, ...
        'NumStreams', numlabs, ...
        'StreamIndices', labindex);
    RandStream.setGlobalStream(stream);
end