Search code examples
c++randomvectorforeachthrust

rand() generating same set of random numbers when called through functors (even after seeding with srand(time(NULL))


I have problem with generating random numbers and I've read through most posts on this topic on SO but none of the solutions seem to work. Please read it through before marking it as a duplicate

I have a functor to generate random numbers between 0.5 and -0.5:

struct randomize
{
    __host__  void operator()( double &x ) const {
        x=(double) (rand() % 1000000) / 1000000 - 0.5;
    }
};

which I'm calling through a for_each like so:

thrust::for_each(myVector.begin(),myVector.end(),randomize());

which in turn is called inside the constructor of a class (lets say myClass) which is called like:

myObjs=std::vector<myClass>(20,myClass(no_of_inputs));

The problem is that all myVectors in all myClass' objects are filled with the same set of values. These values change with each run but are the same across allmyVectors`

I know that rand() is a pseudorandom number generator, and numbers generated by it cannot be expected to be truly random.. But this is too much of a coincidence.

Just to clarify:

  • I'm calling srand(time(NULL)) only once in the entire program.
  • I'm using thrust::for_each and not std::for_each but that should not make much of a difference
  • I know that randomize functor is far from perfect but i'm moding and dividing by 1000000 in order to get a 6 digits after the decimal point. if you could point out a better way to do it, that would be great but please dont get carried away by it.
  • I cannot use c++11 (presently) or boost (at all)
  • I cannot use default constructor for myClass
  • A solution which does not require me to change the structure of the code too much would be more appreciated

Solution

  • myObjs=std::vector<myClass>(20,myClass(no_of_inputs));
    

    Have you defined a copy constructor for myClass that randomizes the data? (Which however would defy the purpose of a copy constructor in my opinion)

    If not, then you are copying the same myClass 20 times into myObj and the vector<myClass> will be constructed by calls to the default copy constructor for each element, which in turn will simply copy the data in myVector.