有时,当您使用常见数据类型(例如双精度数)以非常小的概率进行计算时,数值不准确会在多次计算中级联并导致不正确的结果。因此,建议使用对数概率,这可以提高数值稳定性。我已经在 Java 中实现了对数概率并且我的实现工作,但它的数值稳定性比使用原始双精度差。我的实施有什么问题?在Java中以小概率执行许多连续计算的准确有效的方法是什么?
我无法为这个问题提供一个简洁的演示,因为许多计算的不准确性会级联。然而,这里有一个问题存在的证据:由于数值准确性,提交给 CodeForces 竞赛的文件失败了。运行测试 #7 并添加调试打印清楚地表明,从 1774 天开始,数字错误开始级联,直到概率总和下降到 0(当它应该为 1 时)。在用一个简单的包装器替换我的 Prob 类后,完全相同的解决方案通过了测试。
我的乘法概率的实现:
a * b = Math.log(a) + Math.log(b)
我的加法实现:
a + b = Math.log(a) + Math.log(1 + Math.exp(Math.log(b) - Math.log(a)))
稳定性问题很可能包含在这两行中,但这是我的整个实现:
class Prob {
/** Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = a.logP;
double y = b.logP;
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}