Search code examples
matlabrandomparallel-processingparfor

Different (pseudo) random numbers in parallel loops in Matlab


Asking for random numbers in a parallel loop always return the same pseudo random numbers. How can I avoid this?

% 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

One ideal solution would be to initialize the pseudo random number generator in each thread by CPU time or similar. Things like rng('shuffle') don't seem to help here...

console output:

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 

Solution

  • There is documentation here about various options here. Here's one way you might do something close.

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

    Or, to avoid creating all the streams at the client, you could do this instead:

    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