control random number generator in async programming

조회 수: 2 (최근 30일)
André A
André A 2024년 11월 29일
댓글: Walter Roberson 2024년 12월 4일
My problem is very simple. I am using asynchronous programing to generate random number dependent data.
I would like to have reproducible results, but I can't.
For example:
rng(1);
fA = parfeval(backgroundPool,@rand,1,10000);
B = rand(10000);
wait(fA)
C = max(fetchOutputs(fA),B);
B(1:5)
C(1:5)
If I repeat this code multiple times, only array B is reproducible. I want array C to be reproducible as well. Seems a different random number generator is used there. How can I control that generator?

답변 (1개)

Walter Roberson
Walter Roberson 2024년 11월 29일
parpool are defined to seed random number generators differently. See https://www.mathworks.com/help/parallel-computing/control-random-number-streams-on-workers.html
  댓글 수: 5
André A
André A 2024년 12월 3일
I see. Then if I want to specify a different seed for each worker, how do I proceed? parfevalOnAll seems to only allow to specify the same seed for all workers.
Walter Roberson
Walter Roberson 2024년 12월 4일
NumWorkers = backgroundPool.NumWorkers;
random_seeds = [appropriate list];
F = parfevalOnAll(backgroundPool, @() getCurrentTask().ID, 1);
IDs = fetchOutputs(F);
D = dictonary(IDs, random_seeds);
F = parfevalOnAll(backgroundPool, @() rng(D(getCurrentTask.ID), 'twister'), 0);
fetchOutputs(F);
Now you can
fA = parfevalOnAll(backgroundPool,@rand,1,1,10000);
A = cell(NumWorkers,1);
for idx = 1 : NumWorkers
[~, A{idx}] = fetchNext(fA);
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Background Processing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by