Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: How to set random seed in parfor to produce same results as serial for?

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);

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.

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

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

like image 665
Philipp F Avatar asked Jun 14 '13 14:06

Philipp F


People also ask

How do I reset a random number seed in MATLAB?

If you want to avoid repeating the same random number arrays when MATLAB restarts, then execute the command, rng('shuffle'); before calling rand , randn , randi , or randperm . This command ensures that you do not repeat a result from a previous MATLAB session.

How do you create a random number seed in MATLAB?

rng( seed ) specifies the seed for the MATLAB® random number generator. For example, rng(1) initializes the Mersenne Twister generator using a seed of 1 . The rng function controls the global stream, which determines how the rand , randi , randn , and randperm functions produce a sequence of random numbers.

What is seed in random number generator?

The seed() method is used to initialize the random number generator. The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time.


1 Answers

Ok, I just found the reason:

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'.

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
like image 197
Philipp F Avatar answered Sep 16 '22 11:09

Philipp F