Have you encountered different results using "parfor" vs. "for" loop using Matlab 2019b
11 次查看(过去 30 天)
显示 更早的评论
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 个评论
Edric Ellis
2023-9-12
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 .
回答(1 个)
Rik
2023-9-12
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 个评论
Rik
2023-9-12
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?
另请参阅
类别
在 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!