Stefan Hansen
Stefan Hansen

Reputation: 631

Function returning NaN when it should not

I have defined the following two functions

test <- function(t) {   
   return( (0.5*eta^2/theta)*(1-exp(-2*theta*t)) )   
}

test2 <- function(s,t=s) {   
   return( (0.5*eta^2/theta)*exp(-theta*(s+t))*(exp(2*theta*min(s,t)) - 1) )   
}

and put

> theta=1.2  
> eta=1.8  
> mu=0.2

Now the test-function is defined so that test(t)=test2(t,t). The problem is that the following is returned

> test2(500)   
[1] NaN    
> test(500)    
[1] 1.35

What is wrong here? Thanks in advance.

Upvotes: 2

Views: 1036

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226182

@tomaskrehlik correctly identified the underflow/overflow problem in the original exponential calculation. To avoid the problem, you can rewrite it as:

test3 <- function(s,t=s) {
   return((0.5*eta^2/theta)*exp(-theta*(s+t)+2*theta*min(s,t)) -
      exp(-theta*(s+t)))

In the meantime I am being a little bit baffled about what's going on with that funny return [expression that evaluates to NaN] code in the other answer ... ??

Upvotes: 2

krhlk
krhlk

Reputation: 1594

Probably missing multiplication in the second function, this works for me

test <- function(t) {
   return( (0.5*eta^2/theta)*(1-exp(-2*theta*t)) )
}

test2 <- function(s,t=s) {
   return (0.5*eta^2/theta)*exp(-theta(s+t))*(exp(2*theta*min(s,t)) - 1) 
}

theta=1.2
eta=1.8
mu=0.2

test2(500)
test(500)

Upvotes: 2

Related Questions