For some evil reason I need to calculate the log of the sum of 500 super small probabilities, each term computed by
dmvnorm(X[,i], mean=rep(0,3), sigma=diag(3))
Sometimes the codes above return 0 due to underflow, but using logarithms will be fine.
dmvnorm(X[,i], mean=rep(0,3), sigma=diag(3), log=TRUE)
I know I can handle two terms mathematically: log(p1 + p2) = log(p2) + log(1 + p1/p2)
. But Can we generalize this approach to more terms? Anyone with more experience on this?
BTW, I wrote a recursive function to compute this. Mathematically, it works. But I don't think this is practical.
MESSY <- function (pv)
{
N <- length(pv)
if (N==1)
{return(pv[1])}
else
{w <- pv[N]
pv <- pv[1:N-1]-w
return(w + log(1 + exp(MESSY(pv))))
}
}
Because some p are super small and I can only use w=log(p)
, we have log(exp(w1)+exp(w2)) = w2 + log(1+exp(w1-w2))
and log(exp(w1)+exp(w2)+exp(w3)) = w3 + log(1 + exp(w1-w3) + exp(w2-w3))
for two and three terms.