更新时间:2023-02-10 13:56:59
推力具有可用于生成的随机生成器随机数序列。要与设备向量一起使用它们,您将需要创建一个函子,该函子返回随机生成器序列的另一个元素。最简单的方法是使用计数迭代器的转换。示例(在这种情况下,生成1.0和2.0之间的随机单精度数字)可能像这样:
Thrust has random generators you can use to produce sequences of random numbers. To use them with a device vector you will need to create a functor which returns a different element of the random generator sequence. The most straightforward way to do this is using a transformation of a counting iterator. A very simple complete example (in this case generating random single precision numbers between 1.0 and 2.0) could look like:
#include <thrust/random.h>
#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/iterator/counting_iterator.h>
#include <iostream>
struct prg
{
float a, b;
__host__ __device__
prg(float _a=0.f, float _b=1.f) : a(_a), b(_b) {};
__host__ __device__
float operator()(const unsigned int n) const
{
thrust::default_random_engine rng;
thrust::uniform_real_distribution<float> dist(a, b);
rng.discard(n);
return dist(rng);
}
};
int main(void)
{
const int N = 20;
thrust::device_vector<float> numbers(N);
thrust::counting_iterator<unsigned int> index_sequence_begin(0);
thrust::transform(index_sequence_begin,
index_sequence_begin + N,
numbers.begin(),
prg(1.f,2.f));
for(int i = 0; i < N; i++)
{
std::cout << numbers[i] << std::endl;
}
return 0;
}
在此示例中,函子 prg
将随机数的上限和下限作为参数,默认值为(0.f,1.f)
。请注意,为了使每次调用转换操作都具有不同的向量,应使用初始化为不同起始值的计数迭代器。
In this example, the functor prg
takes the lower and upper bounds of the random number as an argument, with (0.f,1.f)
as the default. Note that in order to have a different vector each time you call the transform operation, you should used a counting iterator initialised to a different starting value.