使用带有测试代码的 std::accumulate 得到了意想不到的结果。我正在尝试添加一个大的双精度向量,但由于某种原因,值溢出:
#include <iostream>
#include <vector>
#include <functional>
#include <numeric>
using namespace std;
double sum(double x, double y)
{
// slows things down but shows the problem:
//cout << x << " + " << y << endl;
return (x+y);
}
double mean(const vector<double> & vec)
{
double result = 0.0;
// works:
//vector<double>::const_iterator it;
//for (it = vec.begin(); it != vec.end(); ++it){
// result += (*it);
//}
// broken:
result = accumulate(vec.begin(), vec.end(), 0, sum);
result /= vec.size();
return result;
}
int main(int argc, char ** argv)
{
const unsigned int num_pts = 100000;
vector<double> vec(num_pts, 0.0);
for (unsigned int i = 0; i < num_pts; ++i){
vec[i] = (double)i;
}
cout << "mean = " << mean(vec) << endl;
return 0;
}
总和内 cout 的部分输出:
2.14739e+09 + 65535
2.14745e+09 + 65536
-2.14748e+09 + 65537
-2.14742e+09 + 65538
-2.14735e+09 + 65539
正确的输出(迭代):
平均值 = 49999.5
不正确的输出(使用累积):
平均值 = 7049.5
我可能犯了一个疲惫的错误?我之前用过累积成功...
谢谢