Question about repeatability in parfor-loop
16 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
I thought that simuation results from a for-loop would be identical to simuation results from a parfor-loop. I am wrong. Granted, the difference is very small (e.g. 1.6098e-15).
Does anyone know the reason for the difference? I am running both for-loop and parfor-loop on the same PC.
Here is my little example to show the difference.
Matrices X1 and X2 are identical since they are both generated by for-loops.
Matrices X1 and X3 are different since X1 comes from for-loop and X3 comes from parfor-loop.
Matrices X3 and X4 are identical since they are both generated by parfor-loops. If this is not true, then I am very confused.
kevin1336()
function kevin1336
%% Run for-loop the first time
N = 100;
X1 = zeros(N, 5);
tic
for iter = 1:N
rng(iter, 'twister')
x = core;
X1(iter, :) = x.';
end
toc
%% Run the same for-loop the second time
X2 = zeros(N, 5);
tic
for iter = 1:N
rng(iter, 'twister')
x = core;
X2(iter, :) = x.';
end
toc
max(abs(X1(:) - X2(:)))
%% Run parfor-loop the first time
X3 = zeros(N, 5);
tic
parfor iter = 1:N
rng(iter, 'twister')
x = core;
X3(iter, :) = x.';
end
toc
max(abs(X1(:) - X3(:)))
%% Run parfor-loop the second time
X4 = zeros(N, 5);
tic
parfor iter = 1:N
rng(iter, 'twister')
x = core;
X4(iter, :) = x.';
end
toc
max(abs(X4(:) - X3(:)))
end
function x = core
M = 1e6;
A = rand(M,5);
b = rand(M,1);
x = A \ b;
end
0 个评论
采纳的回答
Walter Roberson
about 13 hours 前
编辑:Walter Roberson
about 13 hours 前
Inside the parfor, by default each worker only gets a single core, so the \ operation is calculated using a single core.
Inside normal for loops, each worker gets the full complement of cores to automatically parallelize the \ operation over.
The difference in the number of cores results in slight differences in rounding.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!