vendredi 3 décembre 2021

matlab random number generation in parfor loop

I want to generate same normal random numbers for loop and parfor loop. Following MATLAB documentation I tried three different method:

Method 1: Using rng(seed, 'twister')

N = 1;

for ind = 1:10
    rng(ind, 'twister')
    samps(ind) = normrnd(0,1,N,1);
end

plot(samps); hold on

parfor ind = 1:10
    rng(ind, 'twister')
    samps(ind) = normrnd(0,1,N,1);
end

scatter(1:length(samps), samps)
legend({'using for loop', 'using parfor loop'})

By using rng twister method

Method 2: Using RandStream Method

N = 1;
 
sc = parallel.pool.Constant(RandStream('Threefry'));
for ind = 1:10
    stream = sc.Value;
    stream.Substream = ind;
    samps(ind) = normrnd(0,1,N,1);
end

plot(samps); hold on

sc = parallel.pool.Constant(RandStream('Threefry'));
parfor ind = 1:10
       stream = sc.Value;
       stream.Substream = ind;
       samps(ind) = normrnd(0,1,N,1);
end

scatter(1:length(samps), samps)
legend({'using for loop', 'using parfor loop'})

Using Threefry stream-substream method

Method 3: Using another RandStream method

N = 1;
 
stream = RandStream('mrg32k3a');
for ind = 1:10
    stream.Substream = ind;
    samps(ind) = normrnd(0,1,N,1);
end

plot(samps); hold on

stream = RandStream('mrg32k3a');
parfor ind = 1:10
       set(stream,'Substream',ind);
       samps(ind) = normrnd(0,1,N,1);
end

scatter(1:length(samps), samps)
legend({'using for loop', 'using parfor loop'})

Another randStream method

My question is why the last two methods are not working. If I understood MATLAB documentation correctly, they should have worked. Also, is there anything wrong with using rng(seed, 'twister') method with different seeds to produce statistically independent samples?




Aucun commentaire:

Enregistrer un commentaire