为什么循环给出的结果与累积的结果不同?
Why is a Loop Giving Different Results Than accumulate?
我在这里发布了一个实现 Kahan 求和的答案: 我在 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.999999900000000e+00
虽然 for
-循环产生:
2.000000000000000e+00
现场示例 http://coliru.stacked-crooked.com/a/3cb0e3c542303eb4
这是怎么回事?这 2 个的计算结果应该完全 相同的代码!
在 accumulate 示例中,您没有迭代整个值集。 next(cbegin(small))
将从 之后的元素 cbegin(small)
开始。试试这个。
accumulate(cbegin(small), cend(small), big, /*the lambda*/);
我在这里发布了一个实现 Kahan 求和的答案: 我在 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
循环具有相同的结果:
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.999999900000000e+00
虽然 for
-循环产生:
2.000000000000000e+00
现场示例 http://coliru.stacked-crooked.com/a/3cb0e3c542303eb4
这是怎么回事?这 2 个的计算结果应该完全 相同的代码!
在 accumulate 示例中,您没有迭代整个值集。 next(cbegin(small))
将从 之后的元素 cbegin(small)
开始。试试这个。
accumulate(cbegin(small), cend(small), big, /*the lambda*/);