Have you encountered different results using "parfor" vs. "for" loop using Matlab 2019b
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello,
I would like to ask if you have different output results using "parfor" vs. "for" loop especically using the random generator (rng command) with fix seed (both "parfor" and "for" have the same seed).
If so, why is that as I expect the same results for both methods.
Thank you,
Charles
1 comentario
Edric Ellis
el 12 de Sept. de 2023
Please can you post some simple code that reproduces the problem you're seeing. You might also find some insights in this doc page: https://uk.mathworks.com/help/parallel-computing/repeat-random-numbers-in-parfor-loops.html .
Respuestas (1)
Rik
el 12 de Sept. de 2023
Put simply, each worker in the parallel pool inherits the workspace from before the loop.
So if you put your rng before the loop, you should expect different results. If you put the rng call inside the loop, you should expect the same results.
The reason is that each call to a random function influence the current seed. So if your loop contents use random generated data, that means that the iterations are not independent on their order. You should think of a parfor loop as doing this:
N=5;
SomeCode=@(n)disp(n);
v=1:N;
for n=v(randperm(end))
SomeCode(n)
end
If the results of this loop are stable, that means the iterations are independ, which is a requirement for a parfor loop.
With this example it easy why the results are not stable if you put rng outside the loop:
v=v(randperm(end));
old_seed = rng(0);
results=zeros(1,N);
for n=v
results(n)=rand+n;
end
results
rng(old_seed)
v=v(randperm(end));
old_seed = rng(0);
results=zeros(1,N);
for n=v
results(n)=rand+n;
end
results
Now with rng in the loop:
rng(old_seed)
results=zeros(1,N);
for n=v(randperm(end))
rng(n)
results(n)=rand+n;
end
results
results=zeros(1,N);
for n=v(randperm(end))
rng(n)
results(n)=rand+n;
end
results
4 comentarios
Rik
el 12 de Sept. de 2023
My point was that your code should assume such a randperm call. If it doesn't work if you do that, then your code will not have stable results. Did you try my examples with parfor n=1:N?
Thank you for the correction/clarification. While my answer was technically incorrect, can you confirm my intuition that the random state not advancing continuously is likely the source of the issue of OP?
Ver también
Categorías
Más información sobre Parallel for-Loops (parfor) en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!