2014-10-20 107 views
3

我正在測試一些推力代碼,發現transform_reduce給出了一個稍微不同的計算結果,這完全讓我困惑。爲什麼transform_reduce給出的結果與transform&reduce不同?

下面是一個測試示例代碼:(計算總和(EXP(X)))

有人遵守和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; 

} 

我得到的輸出是

transform_reduce result: 474 
transform+reduce result: 476.432 

正確的值應該是476.432 我不知道在transform_reduce中發生了什麼。它不僅給出了一個整數,而且是一個錯誤的答案。不是transform_reduce應該和transform + reduce一樣嗎?

請幫我解釋發生了什麼......

回答

2

從整數改變你的初始化常數:

double d = thrust::transform_reduce(f.begin(), f.end(), exponential<double>(), 0, thrust::plus<double>()); 

爲雙:

double d = thrust::transform_reduce(f.begin(), f.end(), exponential<double>(), 0.0, thrust::plus<double>()); 
                       ^^^ 

transform_reducepicks up its OutputType from the type of this parameter

(順便說一句,您發佈的代碼不會編譯。)

+0

謝謝!我沒有注意到0 -_-。但爲什麼它沒有編譯...我從vs2010複製並粘貼他們 – Chris 2014-10-20 23:06:25

+1

我不認爲這是有效的語法:'cout <<「transform_reduce result:」d << endl;' – 2014-10-20 23:32:14

+0

沒錯。我在這裏添加了它們。愚蠢的錯誤:)但你應該明白我的意思 – Chris 2014-10-23 00:52:02