Why does it takes two calls to rng(seed) to see that the seed was updated?

3 views (last 30 days)
Why does it takes two calls to rng(seed) to see that the seed was updated? Is it a bug?
s = rng(100)
Type: 'twister'
Seed: 0
State: [625x1 uint32]
s = rng(100)
Type: 'twister'
Seed: 100
State: [625x1 uint32]
s = rng(101)
Type: 'twister'
Seed: 100
State: [625x1 uint32]
s = rng(101)
Type: 'twister'
Seed: 101
State: [625x1 uint32]

Answers (3)

Titus Edelhofer
Titus Edelhofer on 18 Aug 2015
Hi,
no, there is a misunderstanding: the call s=rng(100) does two things, namely, setting the seed to 100 and returning the current state before setting the seed. The reason for this is the following "workflow":
% save the current state, and set to seed=100
s = rng(100);
% do some random numbers
x = rand(100, 1);
% restore the state as it was before
rng(s);
You might use RandStream, if you want to create a random number stream object to use.
Titus

Amit
Amit on 18 Aug 2015
Got it
Thx

Chris MacMinn
Chris MacMinn on 10 Nov 2016
What is the motivation for this confusing behavior? It seems quite non-standard... Do any other MATLAB functions behave like this? Surely the command
state = rng(seed);
should always return the new state, not the previous one ?!?
The reason cited above by Titus is a bit silly. The following example achieves the same result, is much less confusing, and is only one line longer:
% save the current state
s = rng();
% set to seed=100
rng(100);
% do some random numbers
x = rand(100, 1);
% restore the state as it was before
rng(s);

Categories

Find more on Random Number Generation in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!