我在这里发布了一个实现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; } )
这应该与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; }
但事实并非如此.给定vector
accumulate
产量:
1.999999900000000e + 00
而for
-loop产量:
2.000000000000000e + 00
实例在 http://coliru.stacked-crooked.com/a/3cb0e3c542303eb4
这里发生了什么?这两个应该评估完全相同的代码!
在累积示例中,您不会迭代整个值集.next(cbegin(small))
将从之后的元素开始 cbegin(small)
.试试这个.
accumulate(cbegin(small), cend(small), big, /*the lambda*/);