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

标签 c++ stl

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

相关文章:

c++ - 在从 Lua 调用的 C++ 中,lua_type(L,0) 返回未记录的 9

c++ - 如何在方法中接收迭代器对?

c++ - 如何在 C++ 中创建自定义的 logic_error 派生类?

c++ - 为什么 `deconstructor` 调用比 `constructor` 调用多?

c++ - 使用STL在相反类别中查找具有匹配属性的元素的算法

c++ - 如何在 Arduino 上将时间设置为中央时区?

c++ - 如何在构造函数中初始化char

c++ - 如何使用 C++11 unique_ptr 实例化我的代码?

c++ - 如何阻止程序跳过 getline?

C++ STL,我想知道映射中的双向迭代器和运算符[]有什么不同