Generate the same random number stream with for and parfor loop
Mostrar comentarios más antiguos
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,
Respuesta aceptada
Más respuestas (1)
Titus Edelhofer
el 26 de Abr. de 2016
1 voto
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
1 comentario
Markus Hofer
el 26 de Abr. de 2016
Categorías
Más información sobre Loops and Conditional Statements 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!