Lin
Lin

Reputation: 195

How to solve this "non-finite function value" in R?

I am using R to calculate a nested functions like this:

C1_B <- function(T){integrate(function(tau)f(tau),lower=0.01*T,upper=0.99*T)$value}

f <- function(tau) {integrate(function(tau1)sqrt(1/(tau-tau1)),lower=0.01*tau,upper=0.99*tau)$value}

C1_B(0.5)

However, I receive a message like

"Error in integrate(function(tau1) sqrt(1/(tau - tau1)), lower = 0.01 * : non-finite function value

In addition: Warning message:**

In sqrt(1/(tau - tau1)) : NaNs produced"

I guess the problem is about the "(tau-tau1)" in my code; but from the integral domain I defined ("lower=0.01*tau,upper=0.99*tau"), (tau-tau1) could not be equal to zero.

Could any body please tell me how can I solve this problem?

Upvotes: 2

Views: 2184

Answers (2)

bdecaf
bdecaf

Reputation: 4732

I gave it a try - the problem is that integrate expects the handed over function to be able to deal with input vectors and output a vector of same size.

Luckily the solution is easy - just wrap your function in sapply.

The following code works:

f <- function(tau) {integrate(function(tau1)sqrt(1/(tau-tau1)),lower=0.01*tau,upper=0.99*tau)$value}

intfun <- function(x) sapply(x,f) 

C1_B <- function(T){integrate(function(tau) intfun(tau),lower=0.01*T,upper=0.99*T)$value}
C1_B(0.5)

Upvotes: 0

Etienne Moerman
Etienne Moerman

Reputation: 331

There exists an exact solution to your integral f. However the value I get does not agree with this numeric approximation. I would say the integral of

    d(tau1)/sqrt(tau - tau1)

is

    -2 * sqrt(tau - tau1)

With you upper bound of 0.99*tau and you lower bound of 0.01*tau you get

    -2 * (sqrt(tau - 0.99 * tau) - sqrt(tau - 0.01 * tau)) = 
    -2 * sqrt(tau) * (sqrt(0.01) - sqrt(0.99))

The integration of that for tau can again be solved exactly. It yields

    -(4/3)(sqrt(0.01) - sqrt(0.99)) * tau^(3/2)

Edit: With your given boundaries 0.01*T and 0.99*T the final resulting solution is

    -(4/3)(sqrt(0.01)-sqrt(0.99)) * ((0.99 * T)^3/2 - (0.01 * T)^3/2)

You can use integrate on the first exact integration result (for f). No error are produced. The errors you report are probably due to the method of approximation. Maybe you could try another integration function that uses another approximation. The exact solution of the function f matches the integral calculated in your program.

When you use integrate to integrate the exact result for f the results are equal to the exact final solution I gave.

Upvotes: 0

Related Questions