std::accumulate 未按预期运行

2024-05-19

我使用 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;
}

sum 内 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

我可能犯了一个令人厌倦的错误?我以前用过accumulate成功过...

Thanks


你需要通过一个double to accumulate:

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

否则使用执行累积int,然后将结果转换为双精度数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

std::accumulate 未按预期运行 的相关文章

随机推荐