tags:

views:

136

answers:

4
double numbers[ ] = { 1, 0.5 ,0.333333 ,0.25 ,0.2, 0.166667, 0.142857, 0.125,
                       0.111111, 0.1 } ;
std::vector<double> doublenumbers ( numbers , numbers + 10 ) ;
std::cout << std::accumulate ( doublenumbers.begin( ) , doublenumbers.end( ) , 0 ) ;

This produces 1, which is evidently wrong. Any explanations ?

Thanks a lot in advance! programmingDoc

+13  A: 

You should write the following:

std::cout << 
 std::accumulate ( doublenumbers.begin( ) , doublenumbers.end( ) , 0.0 ) ;

Because the type of 0 is int.

When std::accumulate is instantiated with the type of the third argument is int, then it would convert the right hand side of the sum. e.g.:

   result += *iter;
// int    += double

This would force a conversion of double to int, instead of what you were thinking of which is the opposite.

AraK
What is amusing is that even using `0.0` there could still be some discrepancies (for large sums) because of the approximate representation of floating numbers. `std::vector<float> v(1000, 1000.1f); std::cout << std::accumulate(v.begin(), v.end(), 0.0f);` yields `1.00011e+06` because float only has 5/6 digits worth of precision on my machine.
Matthieu M.
+3  A: 
std::accumulate ( doublenumbers.begin( ) , doublenumbers.end( ) , .0 ) ;

or

std::accumulate ( doublenumbers.begin( ) , doublenumbers.end( ) , (double) 0 ) ;

The type of the "accumulator" variable is the type of the last argument of std::accumulate. You supplied 0 as an argument - an int literal - which means that the accumulator will have type int. The "accumulation" is done in an int accumulator (i.e. rounded to int after each individual summation) and produces int result. In this case it is, apparently, 1.

AndreyT
+5  A: 

You're calling accumulate with 0 as the init argument, so it'll accumulate using integer maths. Use 0.0 instead.

Oli Charlesworth
A: 
std::accumulate<double> (doublenumbers.begin(), doublenumbers.end(), 0); // also works
no one important
My suspicion is that some template parameters got gobbled. Enclose your code in ticks (`) to keep that from happening.
Dennis Zickefoose
Welcome to Stack Overflow. This would be a better answer if you had mentioned *why* that works, and also if you had drawn attention to what exactly you changed. It's the difference between giving a man a fish and teaching him to fish.
Rob Kennedy
Ahh, if that is what you intended, then I'm not certain that will work. `std::accumulate` takes two template parameters in this case. One to define the iterator type, and one to define the return type. If you only provide one, it will match to the first parameter, and still guess the second.
Dennis Zickefoose