计算log(x - y)给定log(x)和log(y),没有溢出?

时间:2015-04-23 15:00:00

标签: c++ floating-point numeric logarithm

以下函数根据log(x + y)log(x)的值计算log(y),以避免在xy非常大或非常小的情况下出现溢出或下溢:

double log_add(double logx, double logy)
{
    return max(logx, logy) + log1p(exp(-fabs(logx - logy)));
}

必须有类似的log_sub函数来计算log(x - y)。它是什么?

更一般地说,我需要计算log(x - y - z)给定log(x)log(y)log(z)。从log_addlog_sub我可以分两步计算log(x - y - z),但也许有最佳方式?

1 个答案:

答案 0 :(得分:2)

为什么不直接从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));
}

针对您的具体情况:

// 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));
}