function with rand initializes matrix always the s

2019-08-07 01:37发布

问题:

I have a function that should initialize the values of matrix in a random way, given a probability (in this case p(0)=1/3, p(1) = 2/3 ) The problem is that the matrix always comes out to be the same:

void init_matrix(short unsigned* m,int* n_gen)
{
    *n_gen=0;
    int i;
    for(i=0;i<N_X*N_Y;i++) {
        if( ( ( rand() % 100 ) % 3) == 0 )
            m[i]=0;
        else
            m[i]=1;
     }
}

is it because of the implementation of the rand() function? Or am I using it incorrectly? Thanks!

回答1:

You need to call srand in the initial section of your code in order to initialize your random number generator, as the document shows this is typical ways of calling srand:

srand(time(0));

as the document explains:

If rand() is used before any calls to srand(), rand() behaves as if it was seeded with srand(1). Each time rand() is seeded with srand(), it must produce the same sequence of values.

and this part explains why we use time(0):

Standard practice is to use the result of a call to time(0) as the seed. However, time() returns a time_t value, and time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines time_t to be an integral type, and this is also what POSIX requires.



回答2:

You should call srand function to initialize random number generator:

srand(time(NULL));
init_matrix(m, &n_gen); // call your function

For every value passed as argument rand() generates a different succession.