使用具有正弦函数的推力复数(双)向量的麻烦

时间:2016-09-15 11:23:23

标签: cuda thrust

我在设备和主机上的sin复数双向量上使用Thrust函数时遇到一些问题:它看起来像是在浮点数中完成的。

使用thrust::device_vector< thrust::complex<double> >thrust::host_vector< thrust::complex<double> >,我获得:

sin( 1+0i ) == (0.8414709568023682,0)

std::complex<double>

sin( 1+0i ) == (0.8414709848078965,0)

std::complex<float>

sin( 1+0i ) == (0.8414709568023682,0)

我在代码中犯了什么错误?在编译过程中我使用了

nvcc test.cu -o test

以下是完整代码:

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/complex.h>
#include <iostream>
#include <iomanip>
#include <complex>
#include <cmath>

template <typename Vector> 
void Print(Vector &V){
  for (int i=0;i<V.size();i++)
    std::cout <<  V[i] << "  ";
  std::cout << "\n";
}

template <typename T>
struct sin_functor : public thrust::unary_function< T , T >
{
  __host__ __device__
  T operator()( T x) const
  {
    return sin( x );
  }
};

template <typename Vector> 
void ThrustComputation(){
  typedef typename Vector::value_type Tvec;
  Vector A(2);
  A[0]=Tvec(1.,0.);A[1]=Tvec(1.,1.);

  std::cout << "A: " << std::endl;
  std::cout << "  ";Print<Vector>(A);

  Vector B(A.size());

  thrust::transform(A.begin(),A.end(),B.begin(), sin_functor<Tvec>());
  std::cout << "B =sin(A): " << std::endl;
  std::cout << "  ";Print<Vector>(B);
}

template <typename T> 
void stdComputation(){
  std::complex<T> sA[2];
  sA[0]=std::complex<T>(1.,0.);
  sA[1]=std::complex<T>(1.,1.);

  std::cout << "sA: " << std::endl;
  std::cout << "  " << sA[0] << "  " << sA[1] << std::endl;
  std::cout << "sin(sA): " << std::endl;
  std::cout << "  " << sin(sA[0]) << "  " << sin(sA[1]) << std::endl;
}


int main(int argc, char **argv)
{  
  std::cout << std::setprecision(16); 
  std::cout << "Thrust: Computation on GPU device (double)\n";
  ThrustComputation<thrust::device_vector< thrust::complex<double> > >();
  std::cout << "Thrust: Computation on host (double)\n";
  ThrustComputation<thrust::host_vector< thrust::complex<double> > >();
  std::cout << "std: Computation (double)\n";
  stdComputation<double>();
  std::cout << "std: Computation (float)\n";
  stdComputation<float>();
  return 0;
}

我电脑上的输出(Ubuntu 14.04 LTS,cuda 7.5)是:

Thrust: Computation on GPU device (double)
A: 
  (1,0)  (1,1)  
B =sin(A): 
  (0.8414709568023682,0)  (1.298457622528076,0.6349639296531677)  
Thrust: Computation on host (double)
A: 
  (1,0)  (1,1)  
B =sin(A): 
  (0.8414709568023682,0)  (1.298457622528076,0.6349639296531677)  
std: Computation (double)
sA: 
  (1,0)  (1,1)
sin(sA): 
  (0.8414709848078965,0)  (1.298457581415977,0.6349639147847361)
std: Computation (float)
sA: 
  (1,0)  (1,1)
sin(sA): 
  (0.8414709568023682,0)  (1.298457503318787,0.6349638700485229)

1 个答案:

答案 0 :(得分:2)

这似乎是推力库中的真正错误。快速扫描github上的代码导致我this,这可能是罪魁祸首。似乎推力的双精度csinh函数,复杂sin所依赖的函数有一个意外的中间转换浮动,这可能导致你观察到的精度损失。正如评论中所建议的那样,您应该将此报告为错误。