Search code examples
rmontecarlo

Running a Monte Carlo simulation in R, and building a vector from it


The goal of the function I am trying to write is to do the following

  1. Randomly choose a number N between 0 and 10.
  2. Evaluate eq(N) = P.
  3. Generate a number L randomly between 0 and 1.
  4. If L > P, we discard this number, but otherwise, we add P to a vector of numbers.
  5. Repeat this a number of times equal to runs, the input of our function.

Trying to run neutronrejector leads to several errors though:

Error: unexpected '=' in:
"  U <- U+1
  if(U ="
>   }
Error: unexpected '}' in "  }"
> }
Error: unexpected '}' in "}"

Those are the error messages. My code is below. Could anyone take a look at this and see what I am doing wrong? I am completely new to writing functions in R, I am more used to using preset packages.

eq = function(x){x*(exp(-x/1.4))}

values <- c()
U <- 0


neutronrejector = function(runs){
  repeat{
  N = runif(1, min=0, max=10)
  P = eq(N)
  L = runif(100, min=0, max=1)  
  ifelse(L > P, , values = c(N, values))
  U = U+1
  if(U = runs) break
  }
}

Solution

  • A few corrections:

    • equality is tested by ==
    • use runif(1,min=0,max=1) to get one random number
    • if statement instead of ifelse
    neutronrejector = function(runs){
      repeat{
        N = runif(1, min=0, max=10)
        P = eq(N)
        L = runif(1, min=0, max=1)  
        if (L > P) values = c(N, values)
        U = U+1
        if(U == runs) break
      }
      values
    }
    
    neutronrejector(10)
    [1] 4.997457 7.699111 7.009196 5.515345 3.422422 9.495239 8.758963 2.209809 6.392655