I just came across this question:
How to expand and compute log(a + b)?
It's closed, presumably because it's a question about math, which generally isn't on topic. But for this particular question, there is a very programming-related issue with solving it in the obvious way: it is very easy to hit underflow or overflow. (This isn't just a hypothetical; it's a well-known issue when implementing e.g. naive Bayes classifiers.)
If the question were rewritten in terms of the under/overflow issue, e.g. something like this:
I am trying to calculate
log(a + b)
givenlog(a)
andlog(b)
. The problem is,log(a)
andlog(b)
are so negative that when I try to calculatea
andb
themselves, they underflow and I getlog(0)
, which is undefined.For
log(a * b)
andlog(a / b)
, this isn't a problem, sincelog(a * b) = log(a) + log(b)
andlog(a / b) = log(a) - log(b)
. Is there a similar way to calculatelog(a + b)
without needinga
andb
themselves, avoiding the underflow?
Would that be an acceptable question for Stack Overflow? If not, what would be the more appropriate site?
(Part of the reason I bring this up is that there is a very programming-specific detail in the proper solution to this question: Most languages have a log1p
function in their standard library that calculates log(1 + x)
, meant to solve exactly the sort of issue above. And there is a correct way to use it in order to preserve the most precision. An answer on math.stackexchange.com would not include such programming details.)