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!
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:
as the document explains:
and this part explains why we use
time(0)
:You should call srand function to initialize random number generator:
For every value passed as argument
rand()
generates a different succession.