0

I was hoping to get some help integrating a function that is based on a random variable. The function is to get an expected value of a continuous distribution.

Here is the code that I have so far.

montecarlo <- function(r,v,t,x,k) {
  y <- rnorm(1)
  e <- (y*(x*exp((-v*sqrt(t)*y)+((r-(.5*v^2))*t))-k))
  MCOP <- exp(-r*t)*integrate(e, lower = -Inf, upper = Inf)
  if((x*exp((-v*sqrt(t)*y)+((r-(.5*v^2))*t))-k) > 0) {
    return(MCOP)
  } else {
    return(0)
  } 
}

If I type in for instance: montecarlo(.03, .65, 3, 34, 30)

I get an error message that reads:

Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'e' of mode 'function' was not found

MLavoie
  • 9,671
  • 41
  • 36
  • 56
Dmitriy
  • 37
  • 7
  • I want to integrate with respect to y all of the other variables x,v,t,r,and k are going to be given. – Dmitriy Jan 21 '17 at 22:37
  • Y is supposed to be a randomly generated number and the function which which I am trying to program will give me the expected value of a continuous distributions (which is the integral from -inf to inf of y*f(y) dy – Dmitriy Jan 21 '17 at 22:42
  • if you read `?integrate` the first parameter is a "an R function ..." Your code is calculating a a value for e. I don't know `integrate` so I cannot advise much, but I think you need to define another function and pass it as a parameter to `integrate` – Andrew Lavers Jan 22 '17 at 00:46

1 Answers1

0

Your code has multiple issues, but the first one causing the error is that e should be a function. Namely, instead of

y = rnorm(1)
e = (y*(x*exp((-v*sqrt(t)*y)+((r-(.5*v^2))*t))-k))

you should have

e = function(y){y*(x*exp((-v*sqrt(t)*y)+((r-(.5*v^2))*t))-k)}
Andrey Shabalin
  • 4,389
  • 1
  • 19
  • 18
  • 1
    Well, `integrate` needs a function as the first argument. And " I want to integrate with respect to y" seems to be a clear indication that `e` should be a function. Maybe this would be enough of a push for the author to move forward. Solving one issue at a time. – Andrey Shabalin Jan 22 '17 at 00:18