Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to generate random numbers in Thrust

📅 2013-Oct-31 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ random number generation, thrust ⬩ 📚 Archive

Thrust has support for many random number generator engines and distributions. For example, the code below generates floating point numbers in the uniform_real_distribution using the default_random_engine. By default, the numbers generated by the uniform real distribution are in the range [0.0, 1.0)

#include <thrust/device_vector.h>
#include <thrust/random.h>

struct GenRand
{
    __device__
    float operator () (int idx)
    {
        thrust::default_random_engine randEng;
        thrust::uniform_real_distribution<float> uniDist;
        randEng.discard(idx);
        return uniDist(randEng);
    }
};

const int randNum = 1000; // Size of vector
thrust::device_vector<float> rVec(randNum);

thrust::transform(
        thrust::make_counting_iterator(0),
        thrust::make_counting_iterator(randNum),
        rVec.begin(),
        GenRand());

Tried with: CUDA 5.5


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧