jeudi 20 juillet 2017

c++ rand() different behaviour within struct

I have noticed strange behaviour from rand()when it is used within a struct.
The code below uses the same expression to get a double between 0 and 1.
The values generated in the std::cout << ( (double) rand() / RAND_MAX ) <<std::endl; statement seem to be random and are distributed over the specified range. The values that are assigned to the struct's x and y variables, don't seem to be distributed the same way.
e.g. running the program 4 times produces [0.96516, 0.965629, 0.965731, 0.965817] for one.x.

Is there an explanation to this?

Note: I'm not interested in other libraries or workarounds. I'd just like to understand why rand() does behave so differently.

Thank you

#include <iostream>
#include <ctime>

struct particle {
    double x = ( (double) rand() / RAND_MAX );
    double y = ( (double) rand() / RAND_MAX );
};

int main(int argc, const char * argv[]) {
    srand( (int) time(NULL) );
    particle one;
    std::cout << one.x <<std::endl;
    std::cout << ( (double) rand() / RAND_MAX ) <<std::endl;
};




Aucun commentaire:

Enregistrer un commentaire