想象一下,您有大量各种大小的浮点数。计算总和的最正确方法是什么,并且误差最小?例如,当数组看起来像这样时:
[1.0, 1e-10, 1e-10, ... 1e-10.0]
然后你用一个简单的循环从左到右加起来,比如
sum = 0
numbers.each do |val|
sum += val
end
每当您将较小的数字相加时,可能会低于精度阈值,因此误差会越来越大。据我所知,最好的方法是对数组进行排序并开始从最低到最高的数字相加,但我想知道是否有更好的方法(更快,更精确)?
编辑:感谢您的回答,我现在有一个工作代码可以完美地总结 Java 中的双精度值。它是来自获胜答案的 Python 帖子的直接端口。该解决方案通过了我所有的单元测试。(这里有一个更长但经过优化的版本Summarizer.java)
/**
* Adds up numbers in an array with perfect precision, and in O(n).
*
* @see http://code.activestate.com/recipes/393090/
*/
public class Summarizer {
/**
* Perfectly sums up numbers, without rounding errors (if at all possible).
*
* @param values
* The values to sum up.
* @return The sum.
*/
public static double msum(double... values) {
List<Double> partials = new ArrayList<Double>();
for (double x : values) {
int i = 0;
for (double y : partials) {
if (Math.abs(x) < Math.abs(y)) {
double tmp = x;
x = y;
y = tmp;
}
double hi = x + y;
double lo = y - (hi - x);
if (lo != 0.0) {
partials.set(i, lo);
++i;
}
x = hi;
}
if (i < partials.size()) {
partials.set(i, x);
partials.subList(i + 1, partials.size()).clear();
} else {
partials.add(x);
}
}
return sum(partials);
}
/**
* Sums up the rest of the partial numbers which cannot be summed up without
* loss of precision.
*/
public static double sum(Collection<Double> values) {
double s = 0.0;
for (Double d : values) {
s += d;
}
return s;
}
}