randn not random in parfor loops

14 views (last 30 days)
Lorenzo
Lorenzo on 9 Nov 2012
Commented: John Fox on 20 Jul 2017
I hope I'm wrong guys,
I try a PARFOR loop with r2011b and I get a non random result (same non random walks [differents in the result set but same if I relaunch the execution])
code pattern //////
matlabpool local 8; parfor i1 = 1:100 ret = randn(1,5000); .......
//////////////
is there any bugs with this version?
it's enough to take off "matlabpool local 8;" in order to get a random result
Reg
Lorenzo
  1 Comment
John Fox
John Fox on 20 Jul 2017
I had the exact same problem. My for loops gave a different answer than my parfor loops. The reason is
As described in Control Random Number Streams, each worker in a cluster has an independent random number generator stream. By default, therefore, each worker in a pool, and each iteration in a parfor-loop has a unique, independent set of random numbers. Subsequent runs of the parfor-loop generate different numbers.
I fixed this with rng(123,'twister'). At least this worked for me.

Sign in to comment.

Answers (1)

Daniel Shub
Daniel Shub on 9 Nov 2012
You are correct and this is a good thing and consistent with the idea that MATLAB uses the same "seed" every time it starts. Peter Perkins gives a work around on Loren's blog
In that comment he says that
stream = RandStream('mrg32k3a');
parfor ii = 1:10
set(stream,'Substream',ii);
par(ii) = rand(stream);
end
will give the same result as
stream = RandStream('mrg32k3a');
for ii = 1:10
set(stream,'Substream',ii);
par(ii) = rand(stream);
end
he then goes on to talk about independent streams.

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!