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

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 に答える