# Consistently generating same random sequence with for and parfor loop

32 views (last 30 days)
sulav duwal on 30 Oct 2017
Edited: Robert on 6 Nov 2017
Dear all,
I encountered a problem, when I was running monte-carlo simulation. In order to speed up the simulation, I decided to change 'for' loop to 'parfor'. In order to debug and to later check the details of trajectory, I fixed the seed for random number generator within the loop. To my surprise, though the seeds for random number generator in 'for' and 'parfor' loop are same, the random number sequence are completely different. This creates a problem, since I cannot check the trajectories in 'parfor'.
% sample code with 'for' loop
rng(5)
seedForSimulation = randi(100,1,10);
randomNrs = NaN(1,10);
Seeds = NaN(1,10);
for i = 1:10
rng(SeedForSimulation(1,i));
Seeds(i) = SeedForSimulation(1,i);
randomNrs(i) = randi(10);
end
display(Seeds)
display(randomNrs)
The result that I get is :
Seeds = 23 88 21 92 49 62 77 52 30 19
randomNrs = 6 7 1 9 4 1 10 9 7 1
Whereas the same code with 'parfor'
% code
rng(5)
seedForSimulation = randi(100,1,10);
randomNrs = NaN(1,10);
Seeds = NaN(1,10);
parfor i = 1:10
rng(SeedForSimulation(1,i));
Seeds(i) = SeedForSimulation(1,i);
randomNrs(i) = randi(10);
end
display(Seeds)
display(randomNrs)
The result that I get :
Seeds = 23 88 21 92 49 62 77 52 30 19
randomNrs = 5 4 9 5 4 4 10 7 8 4
Though the seeds are same within 'for' and 'parfor', I get different random numbers. Can someone explain me what is Matlab doing ? How can I circumvent the problem.

Robert on 30 Oct 2017
Edited: Robert on 30 Oct 2017
You can produce the same random numbers in a parfor loop if you explicitly set the random number generator type to be the same in the for and parfor loops.
You can do this when you set the seed or before the loop.
parfor i = 1:10
rng(seedForSimulation(1, i), 'twister');
Seeds(1, i) = seedForSimulation(1, i);
randomNrs(1, i) = randi(10);
end
This will return the exact same result if you replace parfor with for. You could also use:
spmd % run once on each parallel worker
rng(0, 'twister')
end
parfor i = 1:10
rng(seedForSimulation(1, i)); % no need to specify again
Seeds(1, i) = seedForSimulation(1, i);
randomNrs(1, i) = randi(10);
end
This will also return the same result as would the for loop.
sulav duwal on 30 Oct 2017
Thanks Robert !!