2

我现在正在学习推力。我有一个问题:如何用推力正常化?我有一个有效的代码,但我想知道这是否是最佳方法。

struct square
{
__host__ __device__
float operator() (float x)
{
    return x * x;
}
};




thrust::device_vector<float> d_x(2);
thrust::device_vector<float> d_y(2);
thrust::device_vector<float> d_z(2);
d_x[0] = 3;
d_x[1] = 4;
square<float>        unary_op;
thrust::plus<float> binary_op;
 float init = 0;

// compute norm
float norm = std::sqrt( thrust::transform_reduce(d_x.begin(), d_x.end(), unary_op, init, binary_op) );
thrust::fill(d_y.begin(), d_y.end(), 1/norm);
thrust::transform(d_x.begin(), d_x.end(), d_y.begin(), d_z.begin(), thrust::multiplies<float>());
4

1 回答 1

3

这应该更有效,因为它不需要为 or 使用存储或d_y带宽d_z

#include <thrust/device_vector.h>
#include <thrust/inner_product.h>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <cmath>

int main()
{
  thrust::device_vector<float> d_x(2);
  d_x[0] = 3;
  d_x[1] = 4;

  float norm = std::sqrt(thrust::inner_product(d_x.begin(), d_x.end()));

  using namespace thrust::placeholders;
  thrust::transform(d_x.begin(), d_x.end(), d_x.begin(), _1 /= norm);

  return 0;
}

当然,您需要将问题规模扩大几个数量级。

于 2012-12-03T20:44:56.077 回答