2009-12-15

A floating point and C++ templates

Find a bug in the following line:
double sum = std::accumulate(V.begin(), V.end(), 0);


Think more...


This bug can't be easiliy avoided as the connection between internal accumulator variable, return value and third argument types is not obvious and is very well incapsulated by implementation.

The right answer is:
double sum = std::accumulate(V.begin(), V.end(), double(0)); //0.L gives off the same effect

Here is GNU implementation of template function in question:

/**
* @brief Accumulate values in a range.
*
* Accumulates the values in the range [first,last) using operator+(). The
* initial value is @a init. The values are processed in order.
*
* @param first Start of range.
* @param last End of range.
* @param init Starting value to add other values to.
* @return The final sum.
*/
template
inline _Tp
accumulate(_InputIterator __first, _InputIterator __last, _Tp __init)
{
// concept requirements
__glibcxx_function_requires(_InputIteratorConcept<_InputIterator>)
__glibcxx_requires_valid_range(__first, __last);

for (; __first != __last; ++__first)
__init = __init + *__first;
return __init;
}