dpois(0,0,true) returns NaN

25 views
Skip to first unread message

Richard Chandler

unread,
Aug 6, 2025, 8:32:14 AMAug 6
to TMB Users
In TMB, dpios(0,0,true) returns NaN. Would you consider changing the behavior to match R where dpois(0,0,TRUE) returns 0?

Here's an example demonstrating the NaN issue. 

## C++ file, named "test_dpois.cpp"
```
#include <TMB.hpp>
template<class Type>
Type objective_function<Type>::operator() ()
{
  DATA_VECTOR(y);
  PARAMETER(lam);
  Type ld;
  ld = dpois(y(0), lam, true);
  return -ld;
}
```


## R file
```
library(TMB)

dat <- list(y=0)

compile("test_dpois.cpp")
dyn.load("test_dpois.so")

## If you change from lam=0.0 to lam=0.1, obj$fn(0) will return 0 for some reason
obj <- MakeADFun(data=dat, parameters=list(lam=0.0), DLL="test_dpois")

obj$fn(0) # Returns NaN
```

I can avoid the NaN problem by using a custom function like this: 

```
template<class Type>
Type dpois2(Type x, Type lambda){
  if(x == 0) {
    return -lambda;
  } else
    // return dpois(x, lambda, true);
    return x*log(lambda) - lambda - lgamma(x+1);
}
```


Kasper Kristensen

unread,
Aug 6, 2025, 9:04:32 AMAug 6
to TMB Users
It works as expected when compiled with 'TMBad':

compile("test_dpois.cpp", framework="TMBad")

without changing the implementation of dpois.

Richard Chandler

unread,
Aug 7, 2025, 9:39:49 AMAug 7
to TMB Users
Thanks, I'll test that out. The dpois2 hack seems to work fine as well. 
Reply all
Reply to author
Forward
0 new messages