生成随机数序列

时间:2018-03-22 00:43:18

标签: r

我需要创建一个包含五个变量的函数,

  • a(乘数)
  • n(样本量)
  • c(默认值为0)
  • m(模数)
  • x0(初始种子值)

我需要用等式

生成一系列随机数
  • xi =(a * xi-1 + c)(mod m),i = 1,2,...,n

与向量x =(x1,...,xn)相同。

我的尝试:



my.unif1 <- function(n, a,c = 0, m, x = x[0]) {
  while(n > 0) {
    x[n] <- (a*x[n-1]+c)%%m
  }
}
&#13;
&#13;
&#13;

请不要仅仅因为我愚蠢而且根本不理解编码,因为如果你有理由至少让我知道它是什么,那么我将来可以修复它。感谢任何提前帮助的人:)。

2 个答案:

答案 0 :(得分:1)

听起来您想要了解有关线性同余发生器的更多信息。这是一个可能帮助您解决代码问题的资源:https://qualityandinnovation.com/2015/03/03/a-linear-congruential-generator-lcg-in-r/

lcg <- function(a,c,m,run.length,seed) {
    x <- rep(0,run.length)
    x[1] <- seed
    for (i in 1:(run.length-1)) {
       x[i+1] <- (a * x[i] + c) %% m
    }
    U <- x/m # scale all of the x's to
         # produce uniformly distributed
         # random numbers between [0,1)
    return(list(x=x,U=U))
}

> z <- lcg(6,7,23,20,5)
> z
$x
[1] 5 14 22 1 13 16 11 4 8 9 15 5 14 22 1 13 16 11
[19] 4 8

$U
[1] 0.21739130 0.60869565 0.95652174 0.04347826 0.56521739
[6] 0.69565217 0.47826087 0.17391304 0.34782609 0.39130435
[11] 0.65217391 0.21739130 0.60869565 0.95652174 0.04347826
[16] 0.56521739 0.69565217 0.47826087 0.17391304 0.34782609

答案 1 :(得分:1)

这可能有所帮助:

my.fct.1 <- function(x, multiplier, increment, modulus){
  increment <- ifelse(missing(increment), 0, increment) # setting the default increment to 0
  newval <- (multiplier*x + increment) %% modulus
  return(newval)
}

my.fct.2 <- function(x0, n, multiplier, increment, modulus){
  if(n == 1){
    val <- my.fct.1(x = x0, multiplier = multiplier, increment = increment, modulus = modulus)
    vec <- c(x0, val)
    return(vec)
  }
  if(n > 1){
    vec <- my.fct.2(x = x0, n = n-1, multiplier = multiplier, increment = increment, modulus = modulus)
    val <- vec[length(vec)]
    newval <- my.fct.1(x = val, multiplier = multiplier, increment = increment, modulus = modulus)
    newvec <- c(vec, newval)
    return(newvec)
  }

}

my.fct.2执行必需的,参数几乎是自我解释的。但请注意,因为它是一个递归函数(可以影响其他事物的速度)。

以下是此类生成序列的一些示例:

> my.fct.2(3, 9, 7, -1, 4)
 [1] 3 0 3 0 3 0 3 0 3 0
> my.fct.2(1, 9, 2, 1, 13)
 [1]  1  3  7  2  5 11 10  8  4  9
> my.fct.2(0, 17, 5, 3, 7)
 [1] 0 3 4 2 6 5 0 3 4 2 6 5 0 3 4 2 6 5
# and here the arguments set to cross check it against @mysteRious's answer
> my.fct.2(5, 20, 6, 7, 23)
 [1]  5 14 22  1 13 16 11  4  8  9 15  5 14 22  1 13 16 11  4  8  9
U <- my.fct.2(5, 20, 6, 7, 23)/23
> U
 [1] 0.21739130 0.60869565 0.95652174 0.04347826 0.56521739 0.69565217 0.47826087 0.17391304
 [9] 0.34782609 0.39130435 0.65217391 0.21739130 0.60869565 0.95652174 0.04347826 0.56521739
 [17] 0.69565217 0.47826087 0.17391304 0.34782609 0.39130435