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

2 次查看(过去 30 天)
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]

回答(3 个)

Titus Edelhofer
Titus Edelhofer 2015-8-18
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 2015-8-18
Got it
Thx

Chris MacMinn
Chris MacMinn 2016-11-10
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);

类别

Help CenterFile Exchange 中查找有关 Random Number Generation 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by