gpt4 book ai didi

c++ - std::accumulate 未按预期行事

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:04 25 4
gpt4 key购买 nike

我在测试代码中使用 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成功...

谢谢

最佳答案

你需要传递一个doubleaccumulate:

result = accumulate(vec.begin(), vec.end(), 0.0, sum);
^^^

否则使用int进行累加,然后将结果转换为double。

关于c++ - std::accumulate 未按预期行事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16950289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com