Consistently generating same random sequence with for and parfor loop
古いコメントを表示
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.
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!