kaskr / adcomp

AD computation with Template Model Builder (TMB)
Other
178 stars 81 forks source link

`dmultinom` cause NaN when zeros are present in `p` #372

Closed Craig44 closed 1 year ago

Craig44 commented 1 year ago

I recently came across NaN behavior when applying TMBs built in dmultinom density function. This was caused because of a zero in one of the probabilities p container. This is expected because of the log(p) call in the source code see here.

In R's dmultinom function they exclude density evaluations where p = 0. Would this be good to add? The alternative is to add a zerofun like function that would add an increment to p to prevent the case p = 0.

For anyone interested I wrote a function called dmultinom_upd which excludes density evaluations when p = 0. See the zipped file for cpp and R script that tests it against TMBs built in dmultinom method.

TMB Version:

‘1.9.1’

R Version:

R version 4.2.1

Operating System:

Windows 10

testmultinomial.zip

Craig44 commented 1 year ago

I over looked R dmultinom which expects x = 0 if p = 0 otherwise it will return Inf. So NaN is probably reasonable

i0 <- prob == 0
if (any(x[i0] != 0)) 
      return(if (log) -Inf else 0)