作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在测试代码中使用 std::accumulate 得到了意想不到的结果。我正在尝试添加一个大的 double vector ,但由于某种原因,该值溢出了:
#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
正确的输出(迭代):
mean = 49999.5
不正确的输出(使用accumulate):
mean = 7049.5
我可能犯了一个令人厌倦的错误?我之前用过accumulate成功...
谢谢
最佳答案
你需要传递一个double
给accumulate
:
result = accumulate(vec.begin(), vec.end(), 0.0, sum);
^^^
否则使用int
进行累加,然后将结果转换为double。
关于c++ - std::accumulate 未按预期行事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16950289/
我是一名优秀的程序员,十分优秀!