为什么循环给出不同的结果而不是积累?

Jon*_*Mee 1 c++ lambda for-loop accumulate

我在这里发布了一个实现Kahan求和的答案:https://stackoverflow.com/a/41743731/2642059我用了一个lambda accumulate:

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;
} )
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

但事实并非如此.给定vector<double> small(10000000, 1e-7) accumulate产量:

1.999999900000000e + 00

for-loop产量:

2.000000000000000e + 00

实例在 http://coliru.stacked-crooked.com/a/3cb0e3c542303eb4

这里发生了什么?这两个应该评估完全相同的代码!

Fra*_*eux 10

在累积示例中,您不会迭代整个值集.next(cbegin(small))将从之后的元素开始 cbegin(small).试试这个.

accumulate(cbegin(small), cend(small), big, /*the lambda*/);
Run Code Online (Sandbox Code Playgroud)