std :: accumulate不按预期工作 [英] std::accumulate not acting as expected

查看:265
本文介绍了std :: accumulate不按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个意想不到的结果使用std :: accumulate与测试代码。我试图添加一个大的向量的双打,但由于某种原因,值溢出:

I am getting an unexpected result using std::accumulate with test code. I am trying to add up a large vector of doubles but for some reason the value is overflowing:

#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内的和:

Partial output from the cout inside the sum:


2.14739e + 09 + 65535

2.14745e + 09 + 65536

-2.14748e + 09 + 65537

-2.14742e + 09 + 65538

-2.14735e + 09 + 65539 ​​

2.14739e+09 + 65535
2.14745e+09 + 65536
-2.14748e+09 + 65537
-2.14742e+09 + 65538
-2.14735e+09 + 65539

正确的输出(迭代):


= 49999.5

mean = 49999.5

输出不正确(使用accumulate):

Incorrect output (using accumulate):


mean = 7049.5

mean = 7049.5

我可能会犯一个累的错误?

I am probably making a tired mistake? I have used accumulate successfully before...

感谢

推荐答案

您需要将 double 传递给 accumulate

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

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

otherwise the accumulation is performed using int, and then converting the result to a double.

这篇关于std :: accumulate不按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆