随机数彼此太相似?

sta*_*oob 1 random r

我使用这段代码生成 3 个随机数,加起来为 72:

# /sf/ask/1739213661/
rand_vect <- function(N, M, sd = 1, pos.only = TRUE) {
    vec <- rnorm(N, M/N, sd)
    if (abs(sum(vec)) < 0.01) vec <- vec + 1
    vec <- round(vec / sum(vec) * M)
    deviation <- M - sum(vec)
    for (. in seq_len(abs(deviation))) {
        vec[i] <- vec[i <- sample(N, 1)] + sign(deviation)
    }
    if (pos.only) while (any(vec < 0)) {
        negs <- vec < 0
        pos  <- vec > 0
        vec[negs][i] <- vec[negs][i <- sample(sum(negs), 1)] + 1
        vec[pos][i]  <- vec[pos ][i <- sample(sum(pos ), 1)] - 1
    }
    vec
}
Run Code Online (Sandbox Code Playgroud)

如果我运行这段代码 100 次:

results <- list()

for (i in 1:100)

{

r_i = rand_vect(3,72)

results[[i]] <- r_i


}
Run Code Online (Sandbox Code Playgroud)

当我查看得出的数字时:

[[1]]
[1] 23 24 25

[[2]]
[1] 25 24 23

[[3]]
[1] 24 25 23

[[4]]
[1] 23 24 25

[[5]]
[1] 25 24 23

[[6]]
[1] 24 24 24

[[7]]
[1] 24 25 23

[[8]]
[1] 24 25 23

[[9]]
[1] 24 25 23

[[10]]
[1] 24 23 25
Run Code Online (Sandbox Code Playgroud)

在每次迭代中,所有数字都按预期加到 72 - 但这些数字并不真正“看起来那么随机”。它们似乎都“聚集”在“24、23、25”周围。我希望在这些数字中看到更多的“随机性”。例如:

[[11]] [1] 5 50 17

[[12]] [1] 12 40 20

  • 为什么我使用的代码中的数字“聚集”在 24、23、25 左右?如何更改上述代码,以便生成的数字具有更多“随机性”?

谢谢你!

And*_*tar 8

如果你只想要三个随机整数,总和为 72,你可以这样做

diff(c(0, sort(sample(72, 2)), 72))
Run Code Online (Sandbox Code Playgroud)

  • @antonoyaro8 它选择两个数字 - 比如说 x 和 y (x &lt;= y ) - 介于 0 和 72 之间,并将序列 (0, x, y, 72) 视为累积序列。然后 `diff` 取这些元素的差,留下 x、yx 和 72-y 作为三个数字。 (3认同)