Consistently generating same random sequence with for and parfor loop
Mostrar comentarios más antiguos
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.
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!