Using R while loop to generate random variables

228 views Asked by At

I want to generate a random variable X by continuing generating U(0,1) random variables as long as their product falls below exp(-2). Then my random variable X would be equal to the number of U(0,1) random variables that was generated minus 1.
I tried using the while loop to do it but not sure why the code does not return anything in my console. Please help me point out what I did wrong?

p <- 1
counter <- 0

while(p < exp(-2)) {
  u <- runif(1)
  p <- p*u
  counter <- counter+1

  X <- counter - 1
  print(X)
}
1

There are 1 answers

3
ThomasIsCoding On BEST ANSWER

update

If you want to replicate the process by 100 times, you can use replicate

replicate(
    100,
    {
        p <- 1
        counter <- 0
        repeat {
            p <- p * runif(1)
            counter <- counter + 1
            if (p < exp(-2)) {
                break
            }
        }
        counter
    }
)

I guess you could use repeat with condition p < exp(-2)

p <- 1
counter <- 0
repeat {
    print(counter)
    p <- p * runif(1)
    counter <- counter + 1
    if (p < exp(-2)) {
        print(counter)
        break
    }
}