Problem with accumulate
You can calculate sum of elements in vector by
1 2 3 4 5 6
|
vector<double> wx;
//... some code of generating data
double x = 0;
for (int i = 0; i < wx.size(); i++)
x += wx[i];
cerr << x << endl;
|
the output is
When I use STL function accumulate from
<numeric>
1 2
|
x = accumulate(wx.begin(), wx.end(), 0);
cerr << x << endl;
|
I receive
What am I doing wrong?
EDIT:
I use gcc version 4.4.1 [gcc-4_4-branch revision 150839] (SUSE Linux)
Last edited on
"Solved" the problem in the following way:
1 2
|
x = 0; zx = accumulate(wx.begin(), wx.end(), 0);
cerr << x << endl;
|
Now it produces correct output. But I don't understand why the previous approach failed.
I will be happy to hear your comments.
Last edited on
Your accumulate performs integer addition. Use accumulate(wx.begin(), wx.end(), 0.0);
to make it floating-point.
Thanks, it solved the whole problem.
Topic archived. No new replies allowed.