Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rand() function in c++ generate even and odd number with a periodic of 3276800 ,who know why?

Tags:

c++

random

for(int j=0;j<2;j++)
{
    for(int i=0;i<3276800;i++)
    {
        cout<<(rand()%2)<<'\n';
    }
    cout<<endl;
}

The first 3276800 and the second 3276800 are the same. The number of rand() is not the same, but the odevity is the same; why?

like image 425
user2737230 Avatar asked Sep 01 '13 12:09

user2737230


1 Answers

The RNG used by most implementations of rand is a linear congruential generator. These tend to have very poor periods in the low-order bits; very naive implementations may have a period of just 2 in the low order bit (i.e. alternating 0 and 1).

Better implementations return only the high 16 bits of the random value, discarding the poor-quality low-order bits. In such an implementation, the low-order bit will have period at most 2^16 = 65536. Since 65536 divides 3276800 evenly, you will see a periodic pattern.

like image 112
nneonneo Avatar answered Nov 15 '22 23:11

nneonneo