为什么循环给出的结果与累积的结果不同

Why is a Loop Giving Different Results Than accumulate?

本文关键字:结果 循环 为什么      更新时间:2023-10-16

我在这里发布了一个实现 Kahan's Sum 的答案: https://stackoverflow.com/a/41743731/2642059 我在 accumulate 中使用了 lambda:

accumulate(next(cbegin(small)), cend(small), big, [c = 0.0](const auto& sum, const auto& input) mutable {
    const auto y = input - c;
    const auto t = sum + y;
    c = t - sum - y;
    return t;
} )

这应该与for -循环具有相同的结果:

auto sum = big;
auto c = 0.0;
for (long i = 0; i < size(small); ++i) {
    const auto y = small[i] - c;
    const auto t = sum + y;
    c = t - sum - y;
    sum = t;
}

但事实并非如此。给定vector<double> small(10000000, 1e-7) accumulate收益率:

1.9999999900000000e+00

虽然for循环产生:

2.000000000000000e

+00

http://coliru.stacked-crooked.com/a/3cb0e3c542303eb4的现场示例

这是怎么回事?这 2 个应该计算出完全相同的代码!

在累积示例中,您不会循环访问整个值集。 next(cbegin(small))将从cbegin(small)之后的元素开始。试试这个。

accumulate(cbegin(small), cend(small), big, /*the lambda*/);