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

后端 未结 1 1271
我寻月下人不归
我寻月下人不归 2021-02-20 12:03
for(int j=0;j<2;j++)
{
    for(int i=0;i<3276800;i++)
    {
        cout<<(rand()%2)<<\'\\n\';
    }
    cout<

The firs

1条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 12:43

    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.

    0 讨论(0)
提交回复
热议问题