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

15 views (last 30 days)
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 Comments
John Fox
John Fox on 20 Jul 2017
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 on 20 Jul 2017
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

Sign in to comment.

Accepted Answer

Edric Ellis
Edric Ellis on 12 Feb 2014
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.

More Answers (0)

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!