假设我们在c++中有一个小 double 数组(约10^(-15))。例如,如果我们按顺序计算此数组中的数字之和

double sum = 0;
for (int i = 0; i < n; i++) sum+=array[i];

我们得到一些值x

但是,如果将数组划分为几个部分,然后计算每个部分的总和,然后将所有部分和相加,我们将得到一些值x2,它接近x,但不完全是x。所以我在计算总和时失去了准确性。

有人知道如何通过将这些数字分成一些部分而不会降低精度来计算小双数的总和吗?

最佳答案

使用Kahan Summation:

#include <numeric>
#include <iostream>
#include <vector>

struct KahanAccumulation
{
    double sum;
    double correction;
};

KahanAccumulation KahanSum(KahanAccumulation accumulation, double value)
{
    KahanAccumulation result;
    double y = value - accumulation.correction;
    double t = accumulation.sum + y;
    result.correction = (t - accumulation.sum) - y;
    result.sum = t;
    return result;
}

int main()
{
    std::vector<double> numbers = {0.01, 0.001, 0.0001, 0.000001, 0.00000000001};
    KahanAccumulation init = {0};
    KahanAccumulation result =
        std::accumulate(numbers.begin(), numbers.end(), init, KahanSum);

    std::cout << "Kahan Sum: " << result.sum << std::endl;
    return 0;
}

输出:
Kahan Sum: 0.011101

代码here

关于c++ - 小双数之和c++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10330002/

10-12 14:15