A very common problem in Markov Chain Monte Carlo involves computing probabilities that are sum of large exponential terms,
$ e^{a_1} + e^{a_2} + ... $
where the components of $a$ can range from very small to very large. My approach has been to factor out the largest exponential term $K := \max_{i}(a_{i})$ so that:
$$a' =K + log\left( e^{a_1 - K} + e^{a_2 - K } + ... \right)$$ $$e^{a'} \equiv e^{a_1} + e^{a_2} + ...$$
This approach is reasonable if all elements of $a$ are large, but not such a good idea if they aren't. Of course, the smaller elements aren't contributing to the floating-point sum anyway, but I'm not sure how to reliably deal with them. In R code, my approach looks like:
if ( max(abs(a)) > max(a) )
K <- min(a)
else
K <- max(a)
ans <- log(sum(exp(a-K))) + K
It seems a common enough problem that there should be a standard solution, but I'm not sure what it is. Thanks for any suggestions.