why the output of randn is different between serial and parallel loop if using function of RNG
조회 수: 1 (최근 30일)
이전 댓글 표시
The outputs of randn are different between serial and parallel loop if using function of RNG with same seed, although they are same in respecive loops. But the outputs of randn are same between serial and parallel loop (this is what I want ), if using randn('state',XXX), which will be not accepted in the future release.
where did I go wrong and how to correct it if I insist on RNG? Thanks in advance for your commnet
My codes as follows(by matlab R2013)
1. the serial file
clc
clear all
delete *.mat
LOOP=4;
for loop=1:LOOP
rng(123);
% randn('state',11)
out=randn(1,1);
save_result(loop,out)
end
2. the parallel file
clc
clear all
delete *.mat
LOOP=4;
cluster_info = parcluster('local');
NumWorkers=cluster_info.NumWorkers;
isOpen = matlabpool('size');
if isOpen>0
matlabpool('close')
end
matlabpool(cluster_info,min(NumWorkers,LOOP));
parfor loop=1:LOOP
rng(123);
% randn('state',11)
out=randn(1,1);
save_result(loop,out)
end
matlabpool('close')
3. the common file
function save_result(loop,out)
save(['RandValue',num2str(loop),'.mat'],'out')
댓글 수: 0
채택된 답변
Titus Edelhofer
2018년 9월 5일
Hi,
interesting. There was one thing missing, namely, that the workers might use a different algorithm (designed to be for the "other" use case). This now works as expected (both serial and all parallel runs give the same results)
function testrng
% init for "serial":
rng('default');
rng(11);
x = randn(10, 1);
% now parallel:
y = zeros(10, 4);
parfor i=1:4
rng('default');
rng(11);
y(:,i) = randn(10, 1);
end
% test
[x y]
diff([x y], 1, 2)
Titus
댓글 수: 0
추가 답변 (3개)
Titus Edelhofer
2018년 9월 4일
Hi,
the idea why the parallel rng gives different answers is, that a common use case is for Monte Carlo simulations with e.g. 100k simulations distributed to ten workers is only wise, if the ten workers each run 10k different simulations. Running ten times the same 10k simulations doesn't make sense. If for your use case it makes sense, take a look at the documentation how to replace the randn call with seed/state. Should be simply
rng(11)
instead of
randn('state', 11);
Titus
댓글 수: 0
H L
2018년 9월 5일
댓글 수: 1
Titus Edelhofer
2018년 9월 5일
Hi,
that makes perfectly sense. As said, often it's desirable to have the different worker different seeds to combine the output. In your case it doesn't, completely agreed.
Titus
참고 항목
카테고리
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!