Generating sequence of random numbers

I need to create a function of five variables,

I need to generate a sequence of random numbers with the equation

As in the vector x = (x1, ..., xn).

My attempt:

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

Upvotes: 1

Views: 163

Answers (2)

niko
niko

Reputation: 5281

That could help:

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 does the required, the arguments are pretty much self explanatory. Watch out though, because it is a recursive function (which can affect speed among other things).

And here are some examples of such generated sequences:

> 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

Upvotes: 1

mysteRious
mysteRious

Reputation: 4294

It sounds like you want to learn more about Linear Congruential Generators. Here's a resource that will probably help you solve your code problem: 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

Upvotes: 2

Related Questions