【问题标题】:Elementwise power operation using CUDA Thrust使用 CUDA Thrust 的 Elementwise 电源操作
【发布时间】:2013-01-16 07:41:42
【问题描述】:

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

【问题讨论】:

  • 你可以编写自己的函子来做到这一点

标签: cuda thrust


【解决方案1】:

请参考 Thrust Quict 入门指南中的Section Transformations,了解如何编写带初始化参数的函子。

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;
        }
};

【讨论】:

    【解决方案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();
    }
    

    【讨论】:

    • 方法operator()返回int而不是double是故意的吗?
    • @SomethingSomething 这是一个错误。固定的。谢谢你通知我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2016-11-07
    • 1970-01-01
    • 2014-09-11
    • 2011-01-24
    • 2016-06-14
    • 2011-07-14
    相关资源
    最近更新 更多