What does command 'rng default;' do?

85 次查看(过去 30 天)
What is the difference with and without this command?

回答(1 个)

jgg
jgg 2016-2-23
编辑:jgg 2016-2-23
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 个评论
Steven Lord
Steven Lord 2018-12-13
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
so we should call those rng defaut right before the first rand and once again before the second rng default?

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by