Main Content

Controlling Random Number Generation

此示例显示了如何使用rngfunction, which provides control over random number generation.

(Pseudo)Random numbers in MATLAB come from the兰德,兰德i, and兰德nfunctions. Many other functions call those three, but those are the fundamental building blocks. All three depend on a single shared random number generator that you can control usingrng

这是important to realize that "random" numbers in MATLAB are not unpredictable at all, but are generated by a deterministic algorithm. The algorithm is designed to be sufficiently complicated so that its outputappearsto be an independent random sequence to someone who does not know the algorithm, and can pass various statistical tests of randomness. The function that is introduced here provides ways to take advantage of the determinism to

  • repeat calculations that involve random numbers, and get the same results, or

  • 确保重复计算中使用不同的随机数

and to take advantage of the apparent randomness to justify combining results from separate calculations.

"Starting Over"

If you look at the output from兰德,兰德i, or兰德nin a new MATLAB session, you'll notice that they return the same sequences of numbers each time you restart MATLAB. It's often useful to be able to reset the random number generator to that startup state, without actually restarting MATLAB. For example, you might want to repeat a calculation that involves random numbers, and get the same result.

rngprovides a very simple way to put the random number generator back to its default settings.

rngdefault兰德% returns the same value as at startup
ans =0.8147

What are the "default" random number settings that MATLAB starts up with, or thatrng default给你?如果您打电话rngwith no inputs, you can see that it is the Mersenne Twister generator algorithm, seeded with 0.

rng
ans =带有字段的结构:类型:'Twister'种子:0状态:[625x1 UINT32]

您将在下面更详细地看到如何使用上述输出,包括State字段,控制和更改MATLAB生成随机数的方式。目前,它是查看什么发电机的一种方式兰德,兰德i, and兰德nare currently using.

不可纠正性

每次打电话兰德,兰德i, or兰德n, they draw a new value from their shared random number generator, and successive values can be treated as statistically independent. But as mentioned above, each time you restart MATLAB those functions are reset and return the same sequences of numbers. Obviously, calculations that use thesame“随机”数字不能被认为是统计独立的。因此,当有必要组合两个或多个matlab会话中完成的计算时,就好像他们一样werestatistically independent, you cannot use the default generator settings.

One simple way to avoid repeating the same random numbers in a new MATLAB session is to choose a different seed for the random number generator.rng通过根据当前时间创建种子,为您提供一种简单的方法。

rngshuffle兰德
ans =0.5971

Each time you use“洗牌”,它用不同的种子重新播放了发电机。你可以打电话rng没有输入来查看实际使用的种子。

rng
ans =带有字段的结构:类型:'Twister'种子:1144302838状态:[625x1 UINT32]
rngshuffle% creates a different seed each timerng
ans =带有字段的结构:Type: 'twister' Seed: 1144302848 State: [625x1 uint32]
兰德
ANS = 0.8089

“洗牌”是一种非常简单的方法,可以重新播放随机数生成器。您可能认为使用它在MATLAB中获得“真实”随机性是一个好主意,甚至是必要的。但是,出于大多数目的不必使用“洗牌”at all。Choosing a seed based on the current time does not improve the statistical properties of the values you'll get from兰德,兰德i, and兰德n,并且不会在任何真正的意义上使它们“更随机”。虽然每次启动MATLAB或运行涉及随机数的大型计算之前,都可以重新播放发电机,这是完全可以的,但实际上,在会话中过于频繁地重新播放发电机并不是一个好主意,因为这可能会影响随机数的统计属性。

What“洗牌”提供的方法是避免重复相同值序列的一种方法。有时这很关键,有时只是“不错”,但通常根本不重要。请记住,如果您使用“洗牌”,您可能需要保存种子rng创建,以便您以后重复计算。您将在下面看到如何做到这一点。

More Control over Repeatability and Non-Repeatability

So far, you've seen how to reset the random number generator to its default settings, and reseed it using a seed that is created using the current time.rngalso provides a way to reseed it using a specific seed.

You can use the same seed several times, to repeat the same calculations. For example, if you run this code twice ...

rng(1)% the seed is any non-negative integer < 2^32x = randn(1,5)
x =1×5-0.6490 1.1812 -0.7585 -1.1096 -0.8456
rng(1) x = randn(1,5)
x =1×5-0.6490 1.1812 -0.7585 -1.1096 -0.8456

…你会得到完全相同的再保险sults. You might do this to recreatexafter having cleared it, so that you can repeat what happens in subsequent calculations that depend onx,使用这些特定值。

On the other hand, you might want to choosedifferent种子以确保您不重复相同的计算。例如,如果您在一个MATLAB会话中运行此代码...

rng(2) x2 = sum(randn(50,1000),1);% 1000 trials of a random walk

还有另一个代码...

rng(3) x3 = sum(randn(50,1000),1);

...您可以将两个结果结合在一起,并确信它们不仅是相同的结果重复两次。

x = [x2 x3];

As with“洗牌”there is a caveat when reseeding MATLAB's random number generator, because it affects all subsequent output from兰德,兰德i, and兰德n。除非您需要可重复性或唯一性,否则通常建议简单地生成随机值而无需重新发电器。如果您确实需要重新播放发电机,通常最好在命令行或代码中不容易忽略的位置完成。

Choosing a Generator Type

Not only can you reseed the random number generator as shown above, you can also choose the type of random number generator that you want to use. Different generator types produce different sequences of random numbers, and you might, for example, choose a specific type because of its statistical properties. Or you might need to recreate results from an older version of MATLAB that used a different default generator type.

One other common reason for choosing the generator type is that you are writing a validation test that generates "random" input data, and you need to guarantee that your test can always expect exactly the same predictable result. If you callrngwith a seed before creating the input data, it reseeds the random number generator. But if the generator type has been changed for some reason, then the output from兰德,兰德i, and兰德nwill not be what you expect from that seed. Therefore, to be 100% certain of repeatability, you can also specify a generator type.

例如,

rng(0,'twister')

原因兰德,兰德i, and兰德nto use the Mersenne Twister generator algorithm, after seeding it with 0.

Using“ combrecursive'

rng(0,“ combrecursive')

selects the Combined Multiple Recursive generator algorithm, which supports some parallel features that the Mersenne Twister does not.

这个命令

rng(0,'v4')

选择MATLAB 4.0中默认值的发电机算法。

当然,此命令将随机数生成器返回其默认设置。

rngdefault

However, because the default random number generator settings may change between MATLAB releases, using'default'不保证长期可预测的结果。'default'is a convenient way to reset the random number generator, but for even more predictability, specify a generator type and a seed.

On the other hand, when you are working interactively and need repeatability, it is simpler, and usually sufficient, to callrng只有种子。

保存和还原随机数生成器设置

打电话rng没有输入,返回一个标量结构,其中包含已经描述的两个信息的字段:生成器类型以及最后一次重新播放发电机的整数。

s = rng
s =带有字段的结构:类型:'Twister'种子:0状态:[625x1 UINT32]

The third field,State, contains a copy of the generator's current state vector. This state vector is the information that the generator maintains internally in order to generate the next value in its sequence of random numbers. Each time you call兰德,兰德i, or兰德n, the generator that they share updates its internal state. Thus, the state vector in the settings structure returned byrngcontains the information necessary to repeat the sequence, beginning from the point at which the state was captured.

While just being able to see this output is informative,rngalso accepts a settings structure as aninput,以便您可以保存设置,包括状态向量,并稍后再还原以重复计算。由于设置包含发电机类型,因此您将确切地知道您要获得的内容,因此“以后”可能意味着从同一MATLAB会话的瞬间到几年(和多个MATLAB版本)的任何意义。您可以从保存生成器设置的随机数序列中的任何点重复结果。例如

x1 = randn(10,10);% move ahead in the random number sequences = rng;% save the settings at this pointx2 = randn(1,5)
x2 =1×50.8404 -0.8880 0.1001 -0.5445 0.3035
x3 = randn(5,5);% move ahead in the random number sequencerng(年代);% return the generator back to the saved statex2 = randn(1,5)% repeat the same numbers
x2 =1×50.8404 -0.8880 0.1001 -0.5445 0.3035

Notice that while reseeding provides only a coarse reinitialization, saving and restoring the generator state using the settings structure allows you to repeatanypart of the random number sequence.

使用设置结构的最常见方法是恢复发电机状态。但是,由于该结构不仅包含状态,还包含发电机类型和种子,因此它也是一种临时切换发电机类型的方便方法。例如,如果您需要使用MATLAB 5.0的旧版生成器之一创建值,则可以在切换使用旧生成器的同时保存当前设置...

previousSettings = rng(0,'v5uniform')
previousSettings =带有字段的结构:类型:'Twister'种子:0状态:[625x1 UINT32]

…and then restore the original settings later.

rng(previousSettings)

You should not modify the contents of any of the fields in a settings structure. In particular, you should not construct your own state vector, or even depend on the format of the generator state.

编写更简单,更灵活,代码

rngallows you to either

  • reseed the random number generator, or

  • 保存和还原随机数生成器设置

without having to know what type it is. You can also return the random number generator to its default settings without having to know what those settings are. While there are situations when you mightwantto specify a generator type,rngaffords you the simplicity of notto specify it.

If you are able to avoid specifying a generator type, your code will automatically adapt to cases where a different generator needs to be used, and will automatically benefit from improved properties in a new default random number generator type.

rngandRandStream

rngprovides a convenient way to control random number generation in MATLAB for the most common needs. However, more complicated situations involving multiple random number streams and parallel random number generation require a more complicated tool. TheRandStreamclass is that tool, and it provides the most powerful way to control random number generation. The two tools are complementary, withrng提供了一种更简单简明的语法RandStream