首页 > 解决方案 > Set.seed() 结合 for 循环

问题描述

我使用以下代码:

set.seed(74)
length = 10
W = rep(0,length)
W[1] = 0
for (i in 1:length){ 
W[i+1] = W[i]+ rnorm(1)
}`

目的是在使用种子 74 时始终生成相同范围的 W。现在,我想添加另一个向量,称为 Z,但保持相同的 W:

set.seed(74)
length = 10
W = rep(0,length)
Z = rep(0,length)
W[1] = 0
Z[1] = 0
for (i in 1:length){ 
W[i+1] = W[i]+ rnorm(1)
Z[i+1] = Z[i] + rnorm(1)
}`

现在,出现了 W 正在改变的问题,但我想要与第一个代码中相同的 W 和一个额外的随机 Z。实际上,我不知道命令 set.seed() 真正在做什么。

我将不胜感激任何帮助。`

标签: r

解决方案


set.seed()设置(伪)随机数生成器的种子,用于生成由 调用的值rnorm()。它可以被认为是生成预先确定的随机数列表的起点。如果你选择一个种子,比如 100(这个值是完全任意的),然后运行

set.seed(100); rnorm(10)

您将获得与将种子设置为相同值并运行相同命令时完全相同的结果。如果您设置不同的种子,您将(可能)得到不同的数字字符串。

Thinking of the random numbers as a long, predetermined list will help you understand why the second block of code produces different values for W than the first block. Imagine that for each random number you draw, you move one down the list. With the first block of code, you select 10 random numbers and set them in W. In the second block of code, you select one random number and set it to W, then another random number and set it to Z, and so on. The positions of the random numbers generated for W are different between the two blocks.; all 10 of them go to W in the first block, but only half of them go to W in the second block (the other half go to Z).

Although, note that W[2] is the same between both blocks; in both cases, this is the first random number generated after setting the seed. The second number goes to Z. In the first block, if you take W[3]-W[2], which gives you value of the second random number drawn after setting the seed, you'll see that this is equal to Z[2] in the second block, which is also the second number drawn after setting the seed.

To get the same results in W each time, you need to make sure the order of the random numbers is respected. This means instead of the second block, you should run the first block once for W and once for Z (only setting the seed once, i.e., only before W).


推荐阅读