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.
In a parfor
-loop, you cannot control what
sequence the iterations execute in, nor can you control which worker
runs which iterations. So even if you reset the random number generators,
the parfor
-loop can generate the same values in
a different sequence.
To reproduce the same set of random numbers in a parfor-loop each time the loop runs, you must control random generation by assigning a particular substream for each iteration.
First, give each worker the same stream, one that supports substreams.
parpool('local',4); spmd rng(0,'combRecursive'); end
Inside the parfor
-loop, set the substream
index by the loop index. This ensures that each iteration uses its
particular set of random numbers, regardless of which worker runs
that iteration or what sequence iterations run in.
r = zeros(1,16); parfor i = 1:16 stream = RandStream.getGlobalStream(); stream.Substream = i; r(i) = rand; end r
r = Columns 1 through 8 0.7270 0.5582 0.1666 0.3477 0.5671 0.5502 0.0130 0.9179 Columns 9 through 16 0.1567 0.7076 0.8577 0.8923 0.0891 0.2413 0.6074 0.2369