Calculate log (x - y) given by log (x) and log (y) without overflow?
The following function calculates log(x + y)
, taking into account the values log(x)
and log(y)
, avoiding overflows or overflows, if x
either y
very large or very small:
double log_add(double logx, double logy)
{
return max(logx, logy) + log1p(exp(-fabs(logx - logy)));
}
There log(x - y)
must be a similar function for the calculation log_sub
. What is it?
More generally, I need to compute log(x - y - z)
given log(x)
, log(y)
and log(z)
. From log_add
and log_sub
I can calculate log(x - y - z)
in two steps, but maybe there is an optimal way?
source to share
Why not just go straight from identities :
double log_add(double logx, double logy) {
return logx + log1p(exp(logy - logx));
}
double log_sub(double logx, double logy) {
return logx + log1p(-exp(logy - logx));
}
In your specific case:
// log(x - y - z) given the three logs
double log_xyz(double logx, double logy, double logz) {
return logx + log1p(-exp(logy - logx) - exp(logz - logx));
}
source to share