std::reduce seems to convert results to integers

The version of std::reduce() that you are calling:

template<class ExecutionPolicy, class ForwardIt, class T, class BinaryOp>
T reduce(ExecutionPolicy&& policy,
         ForwardIt first, ForwardIt last, T init, BinaryOp binary_op);

You can clearly see that the return value uses the same data type as the init parameter, which in your case is being deduced as an int, which is why the result is an int.

To make the return value be a double instead, simply change the literal 0 to 0.0 in the init parameter:

return reduce(execution::seq, cbegin(coeffs), cend(coeffs), 0.0, ...);

If you look at the declaration of std::reduce(), you'll see that the versions of std::reduce() that take an init value as input use its type as the return type. Per cppreference.com, you'll see the following:

template<class InputIt, class T>
T reduce(InputIt first, InputIt last, T init);

or, in your case (Thanks to Remy Lebeau for noticing):

template<class ExecutionPolicy, class ForwardIt, class T, class BinaryOp>
T reduce(ExecutionPolicy&& policy,
         ForwardIt first, ForwardIt last, T init, BinaryOp binary_op);

So, the type of the init value determines the type of the output value, and you are passing an integer literal (i.e. 0). Try passing a double literal instead (i.e. 0.0).


std::accumulate() has the same pitfall. The return type (and type of the accumulator variable) is the same as the type of the init parameter.

Since 0 is an int, the result is also an int. Use 0.0 instead.

Tags:

C++

C++17