Different behaviour of rng() and rand() in parfor-loop

조회 수: 6 (최근 30일)
JonasBGood
JonasBGood 2014년 2월 11일
댓글: Walter Roberson 2023년 1월 31일
Hey folks,
I experienced a different output of the standard function rand() in a parfor-loop although I am using the same seed-value. Example:
>> parfor i = 1:1, rng(123), rand(1,1), end
ans =
0.2751
>> for i = 1:1, rng(123), rand(1,1), end
ans =
0.6965
Is this a bug? I would expect exactly the same output of rand() in parfor.
Thanks & greetings Jonas
------------------------------------------------
ps: here are my detailed version information, I use an Intel i7-2600 processor.
----------------------------------------------------------------------------------------------------
MATLAB Version: 8.2.0.701 (R2013b)
MATLAB License Number: ••••••
Operating System: Microsoft Windows 7 Version 6.1 (Build 7601: Service Pack 1)
Java Version: Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot™ 64-Bit Server VM mixed mode
----------------------------------------------------------------------------------------------------
MATLAB Version 8.2 (R2013b)
DIPUM Toolbox Version 1.1.4
DIPUM Toolbox Version 1.1.3
Image Processing Toolbox Version 8.3 (R2013b)
Optimization Toolbox Version 6.4 (R2013b)
Parallel Computing Toolbox Version 6.3 (R2013b)
  댓글 수: 2
John Fox
John Fox 2017년 7월 20일
I had the exact same problem. My for loops gave a different answer than my parfor loops. The reason is
As described in Control Random Number Streams, each worker in a cluster has an independent random number generator stream. By default, therefore, each worker in a pool, and each iteration in a parfor-loop has a unique, independent set of random numbers. Subsequent runs of the parfor-loop generate different numbers.
I fixed this with rng(123,'twister'). At least this worked for me.
John Fox
John Fox 2017년 7월 20일
Notice what happens when you add 'twister' to the parfor loop
>> for i = 1:1, rng(123), rand(1,1), end
ans =
0.6965
Which is the same answer you got.
>> parfor i = 1:1, rng(123,'twister'), rand(1,1), end
ans =
0.6965
It is the same answer when you add 'twister' to the parfor loop

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

채택된 답변

Edric Ellis
Edric Ellis 2014년 2월 12일
The client and the workers are set up to use different random generators, so this is expected. This is covered in the documentation. Note that "rng(seed)" changes only the seed but not the underlying generator type.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by