Generate the same random number stream with for and parfor loop
1 次查看(过去 30 天)
显示 更早的评论
Dear all,
I have a question concerning random number generation. Is it possible to generate the same random number stream with a for and a parfor loop? Consider the following code example:
clear variables;
spmd
rng(0,'combRecursive');
end
seed = 5;
rng(seed);
for i = 1:4
r(:,i) = randn(4,1);
end
r
Executing this the result will be reproducably:
r = -0.6241 -0.7559 -1.1331 -0.5142
-0.0756 1.4777 0.1639 -1.3629
-0.2618 0.3802 -0.3092 -0.9377
-0.5144 -0.5975 0.0484 -0.2263
On the other hand, if I exchange for with parfor i will get(considering setting the random number generator to 5)
clear variables;
spmd
rng(5,'combRecursive');
end
seed = 5;
rng(seed);
parfor i = 1:4
r(:,i) = randn(4,1);
end
r
r =
-0.7559 -0.6241 -0.6241 -1.1331
1.4777 -0.0756 -0.0756 0.1639
0.3802 -0.2618 -0.2618 -0.3092
-0.5975 -0.5144 -0.5144 0.0484
How can I configure the random number generator in such a way, that parfor and for will give the same random numbers? I did read the documentation in:
- http://de.mathworks.com/help/distcomp/control-random-number-streams.html
- http://de.mathworks.com/help/matlab/examples/controlling-random-number-generation.html
- http://de.mathworks.com/help/distcomp/repeat-random-numbers-in-parfor-loops.html
but unfortunately was not able to achieve this.
Thank you very much. Kind regards,
0 个评论
采纳的回答
Stephen23
2016-4-26
You can't, because the parfor execution order is not specified.
The easiest way to avoid this problem would be to generate all random numbers before the loop, and then use indexing to pick the appropriate slice within each iteration.
更多回答(1 个)
Titus Edelhofer
2016-4-26
Hi,
this can't work by design: the number generator in the client generates 16 random numbers (and reshapes to 4x4 matrix).
The parfor can't generate the same because:
- the seed would have to be set to the value at the end of the random number generation of the previous iteration
- even worse: parfor ordering is arbitrary, such a dependency on order is not allowed
Maybe you can explain a little more why you want to do this ...
Titus
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!