Fabled
Fabled

Reputation:

Usage of optimize in R.

So I have a function w.r.t $x$, that is actually an integral that is evaluated w.r.t $t$. So I made a nested function, but once I try to optimize it i get an annoying error.

I believe it's because the integral needs the assumption $x > 5/2$ in order to be evaluatable. How does one assume parameters in R? Here is my code and the error:

g = function(x){
  f = function(t) {exp(-((x*t)^3))^(1/3)*(1-(1-exp(-((10*x/(2*x-5))*t)^(1/3)))^2)}
  R = integrate(f,0,Inf)
}
g=Vectorize(g)

optimize(g, c(0.1, 10), tol = 0.0001)

ERROR:

Error in optimize(g, c(0.1, 10), tol = 1e-04) : 
  invalid function value in 'optimize'

Doing this with Maple is much easier. Just with [integral] assuming $x >5/2$ I got the answer to be $x=5.258565455$, which is correct.

Any help is much appreciated.

Upvotes: 0

Views: 126

Answers (1)

Dimitris Rizopoulos
Dimitris Rizopoulos

Reputation: 350

The integrate() function in R gives you a list of elements. Logically, you only need the value of the integral, i.e.,

g <- function (x) {
    f <- function (t) exp(-((x*t)^3))^(1/3)*(1-(1-exp(-((10*x/(2*x-5))*t)^(1/3)))^2)
    integrate(f, 0, Inf)$value
}

optimize(g, c(0.1, 10), tol = 0.0001)

Upvotes: 1

Related Questions