从R中的具体分布减少数字生成器的序列

Decreasing sequence of numbers generator from concrete distribution in R

我是 R 的新手,很抱歉,如果我问了一个愚蠢的问题。 我正在尝试从正态分布生成随机数,因为它们将形成递减的数字序列,这意味着当 Y_n < Y_(n+1).

时生成器停止

我知道我必须使用一些 for 和 while 循环,但我不知道如何使用。

非常感谢。

x <- rnorm(2)
i  <- 1
while (x[i] >= x[i+1]){
  x[i+2] <- rnorm(1)
  i <- i + 1
}
if (x[i] < x[i+1]) x <- x[1:i] 

我对这段代码不是很感兴趣,因为它在没有事先分配内存的情况下增长了一个向量(已经很糟糕)(也不好),但我想不出一种方法来做 OP 想要的无需以这种方式增长矢量。另外,我希望 pythonic 有一个 R 词。事实并非如此。不会是 R-ic。但它可以满足您的要求。

像这样:

vals <- rnorm(n = 2)
idx <- length(vals)
while(vals[idx - 1] < vals[idx]) {
  vals <- append(x = vals, values = rnorm(n = 1))
  idx <- idx + 1
}

如果您想 "with high probability" 避免向量增长,您可以批量生成数字。批量大小为 10 时,您已经不太可能需要增长一次向量。

Performance-wise,我不知道哪个更快。

rnormdec <- function(..., batch_size = 10) {
  x <- rnorm(batch_size, ...)
  decreasing <- cummax(diff(x)) < 0

  while (all(decreasing)) {
    x <- c(x, rnorm(batch_size, ...))
    decreasing <- cummax(diff(x)) < 0
  }

  x[c(TRUE, decreasing)]
}

set.seed(1)

runs <- lapply(seq_len(1e5), function(...) rnormdec(10))
table(lengths(runs))
#> 
#>     1     2     3     4     5     6     7     8 
#> 49990 33311 12507  3339   714   116    20     3

reprex package (v0.2.0) 创建于 2018-03-07。