2

有没有办法用pow函数转换推力矢量?换句话说,我想将x向量的每个元素转换为pow(x,a), 并带有a一个常数。

4

2 回答 2

2

有关如何编写具有初始化参数的函子,请参阅Thrust Quict 入门指南中的部分转换。

struct saxpy_functor
{
    const float a;

    saxpy_functor(float _a) : a(_a) {}

    __host__ __device__
        float operator()(const float& x, const float& y) const { 
            return a * x + y;
        }
};
于 2013-01-16T10:23:20.560 回答
2

这是一个完整的例子。正如@Eric 所提到的,所需要的只是定义自己的幂函数并使用thrust::transform.

#include <thrust/sequence.h>
#include <thrust/device_vector.h>

class power_functor {

    double a;

    public:

        power_functor(double a_) { a = a_; }

        __host__ __device__ double operator()(double x) const 
        {
            return pow(x,a);
        }
};

void main() {

    int N = 20;

    thrust::device_vector<double> d_n(N);
    thrust::sequence(d_n.begin(), d_n.end());

    thrust::transform(d_n.begin(),d_n.end(),d_n.begin(),power_functor(2.));

    for (int i=0; i<N; i++) {
        double val = d_n[i];
        printf("Device vector element number %i equal to %f\n",i,val);
    }

    getchar();
}
于 2014-04-29T17:09:11.647 回答