I want to fill a device vector with random values in the range [-3.2, 3.2)
. Here is the code I wrote to generate this:
#include <thrust/random.h>
#include <thrust/device_vector.h>
struct RandGen
{
RandGen() {}
__device__
float operator () (int idx)
{
thrust::default_random_engine randEng(idx);
thrust::uniform_real_distribution<float> uniDist(-3.2, 3.2);
return uniDist(randEng);
}
};
const int num = 1000;
thrust::device_vector<float> rVec(num);
thrust::transform(
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(num),
rVec.begin(),
RandGen());
I find that the vector is filled with values like this:
-3.19986 -3.19986 -3.19971 -3.19957 -3.19942 -3.05629 -3.05643 -3.05657 -3.05672 -3.05686 -3.057
In fact, I could not find a single value that is greater than zero!
Why is this not generating random values from the range I set? How do I fix this?
You have to call randEng.discard()
function to make the behavior random.
__device__ float operator () (int idx)
{
thrust::default_random_engine randEng;
thrust::uniform_real_distribution<float> uniDist(-3.2, 3.2);
randEng.discard(idx);
return uniDist(randEng);
}
P.S: Refer to this answer by talonmies.