What does command 'rng default;' do?
45 views (last 30 days)
Show older comments
What is the difference with and without this command?
0 Comments
Answers (1)
jgg
on 23 Feb 2016
Edited: jgg
on 23 Feb 2016
When Matlab generates random numbers, they're not truly random; they are based on a pseudo-random number generating algorithm. The rng command controls the seed, or starting point, for this value. The "default" values resets it to the original value that MATLAB starts with; this evolves over time.
You can see this behaviour if you do something like called rand(10,1), then calling rng('default') then repeating the rand command. It will generate exactly the same "random" numbers.
This is generally useful for situations where you want to repeat an (ex ante) random outcome. For instance, in Monte Carlo simulation or in simulation-based optimization procedures.
3 Comments
Steven Lord
on 13 Dec 2018
That could happen if you didn't reset the random number generator to the default both before and after the first call, or you didn't store the generate before the first call and restore it after that first call. This does the former:
rng default
x1 = rand(1, 10);
rng default
x2 = rand(1, 10);
isequal(x1, x2) % true
This does the latter:
oldstate = rng;
x3 = rand(1, 10);
rng(oldstate);
x4 = rand(1, 10);
isequal(x3, x4) % true
If instead you'd done this:
x5 = rand(1, 10);
x6 = rand(1, 10);
rng default
x7 = rand(1, 10);
there's no guarantee that x7 would be equal to x5 or x6. It would depend on the state of the random number generator before the line that defined x5. If you ran those four lines of code immediately after starting MATLAB or immediately after rng default, x5 and x7 would be the same. It's extremely unlikely that x6 and x7 would be the same.
x7 would be equal to x1 and x2, however.
isequal(x5, x7) % possibly true, probably false
isequal(x6, x7) % almost certainly false
isequal(x1, x7) % true
isequal(x2, x7) % true
Bachtiar Muhammad Lubis
on 20 Dec 2018
so we should call those rng defaut right before the first rand and once again before the second rng default?
See Also
Categories
Find more on Random Number Generation 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!