Error while integrating a real function

Asked

Viewed 30 times

4

I’m trying to integrate, under the whole line, the function:

integrand_1<-function(x){
  exp(-x/phi-y*exp(-x)/(phi*2)-(x+sigma2/2)^2/(2*sigma2))}

Using the following data:

df <- readRDS(url("https://rawcdn.githack.com/fsbmat/StackOverflow/db2ff43778b047eab9761cdedb16f70a08ec2f89/df.rds"))
phi <- 0.02216155
rho <- 0.6003019
sigma2 <- 0.02652626
y <- df$y
mu <- df$mu

To do this, use the function Integrate, as below:

integrate(Vectorize(integrand_1), -Inf, Inf)$value

However, I receive the following message:

Error in integrate(Vectorize(integrand_1), -Inf, Inf) : 
  evaluation of function gave a result of wrong length

I tried to visualize the function to see if there was something wrong, using that code:

x <- seq(-10,10, length=300)
integrand_1(x)
is.numeric(integrand_1(x))
plot(x,integrand_1(x), xlim = c(2.3,2.6), type = "l")

The generated graph was:

inserir a descrição da imagem aqui

That is, it was not to generate the above error. Or at least do not understand the reason for the mistake. Someone, could help me?

1 answer

6


The function integrate is defined as

Adaptive Quadrature of functions of one variable over a Finite or Infinite interval

In particular, see how she defines the integrating f (griffins of mine):

an R Function taking a Numeric first argument and returning a Numeric vector of the same length. Returning a non-finite element will generate an error.

The function defined in integrand_1 possesses y in its definition, in addition to x. That way, when entering some value x of a dimension, it returns a response equal in size to y, whereas in this specific case it is 300:

integrand_1 <- function(x){
  exp(-x/phi-y*exp(-x)/(phi*2)-(x+sigma2/2)^2/(2*sigma2))
}

integrand_1(0)

  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [39] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [77] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[115] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[153] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[191] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[229] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[267] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

So review whether y really needs to be informed as a vector for integrand_1. Maybe integrate is not the proper function to solve this problem, because it has the greatest face of being something multivariate.

  • 1

    Hi Prof. Marcus Nunes, in fact you are right, the y is a vector. I was believing that this should not be a problem for the calculation. I’ll see what I can do! Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.