Why does transform_reduce give a different result than transform & reduce?
I tested some pull code and found that transform_reduce gives a slightly different computation result which completely confused me.
Here's an example test code: (for calculating the sum (exp (x)))
It has been executed and launched in VS2012 + CUDA 6.0
#include <iostream>
#include <cmath>
#include <thrust/device_vector.h>
using namespace std;
template <typename T>
struct exponential
{
__host__ __device__
T operator()(const T& x) const {
return exp(x);
}
};
void main() {
thrust::device_vector<double> f(7), g(7);
f[0]=0.0; f[1]=1.0; f[2]=2.0; f[3]=3.0; f[4]=5.0; f[5]=5.0; f[6]=5.0;
double d = thrust::transform_reduce(f.begin(), f.end(), exponential<double>(), 0, thrust::plus<double>());
cout<<"transform_reduce result: " d<<endl;
thrust::transform(f.begin(), f.end(), g.begin(), exponential<double>());
double e = thrust::reduce(g.begin(), g.end());
cout<<"transform+reduce result: "<<e;
}
The way out I got was that
transform_reduce result: 474
transform+reduce result: 476.432
The correct value should be 476.432 I don't know what happened in transform_reduce. This not only gives an integer but also the wrong answer. Doesn't mean transform_reduce should be the same as transform + reduce?
Please help me explain what happened ...
source to share
Change the initialization constant to an integer:
double d = thrust::transform_reduce(f.begin(), f.end(), exponential<double>(), 0, thrust::plus<double>());
to double:
double d = thrust::transform_reduce(f.begin(), f.end(), exponential<double>(), 0.0, thrust::plus<double>());
^^^
transform_reduce
selects its OutputType from the type of this parameter .
(By the way, the code you posted won't compile.)
source to share