我正在尝试在相对精度较低的双精度浮点中实现以下功能:
这在统计应用程序中被广泛使用以添加在对数空间中表示的概率或概率密度。当然,或都很容易溢出或下溢,这很不好,因为日志空间最初是用来避免下溢的。这是典型的解决方案:
Cancellation from does happen, but is mitigated by . Worse by far is when and are close. Here's a relative error plot:
The plot is cut off at to emphasize the shape of the curve , about which the cancellation occurs. I've seen error up to and suspect that it gets much worse. (FWIW, the "ground truth" function is implemented using MPFR's arbitrary-precision floats with 128-bit precision.)
I've tried other reformulations, all with the same result. With as the outer expression, the same error occurs by taking a log of something near 1. With as the outer expression, cancellation happens in the inner expression.
Now, the absolute error is very small, so has very small relative error (within an epsilon). One might argue that, because a user of is really interested in probabilities (not log probabilities), this terrible relative error isn't a problem. It's likely that it usually isn't, but I'm writing a library function, and I'd like its clients to be able to count on relative error not much worse than rounding error.
It seems I need a new approach. What might it be?