使用 Thrust 生成均匀分布的随机数

Generating random numbers with uniform distribution using Thrust(使用 Thrust 生成均匀分布的随机数)

本文介绍了使用 Thrust 生成均匀分布的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Thrust 生成一个介于 0.01.0 之间的随机数向量.我能找到的唯一记录示例会产生非常大的随机数(thrust::generate(myvector.begin(), myvector.end(), rand).我确信答案很简单,但如果有任何建议,我将不胜感激.

I need to generate a vector with random numbers between 0.0 and 1.0 using Thrust. The only documented example I could find produces very large random numbers (thrust::generate(myvector.begin(), myvector.end(), rand). I'm sure the answer is simple, but I would appreciate any suggestions.

推荐答案

Thrust 有随机生成器,可用于生成随机数序列.要将它们与设备向量一起使用,您需要创建一个函子,该函子返回随机生成器序列的不同元素.最直接的方法是使用计数迭代器的转换.一个非常简单的完整示例(在这种情况下生成 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.

这篇关于使用 Thrust 生成均匀分布的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 Thrust 生成均匀分布的随机数

基础教程推荐