rand()函数在c ++中产生偶数和奇数,周期为3276800,谁知道为什么? [英] rand() function in c++ generate even and odd number with a periodic of 3276800 ,who know why?

查看:590
本文介绍了rand()函数在c ++中产生偶数和奇数,周期为3276800,谁知道为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

第一个3276800和第二个3276800是相同的。
rand()的数目不相同,但是odevity是相同的;
为什么? $

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?

推荐答案

rand 线性同余生成器 。这些在低阶位中往往具有非常差的周期;非常幼稚的实现可能在低阶位(即交替的0和1)中具有仅为2的周期。

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).

更好的实现仅返回随机值的高16位,丢弃低质量低位比特。在这样的实现中,低阶位将具有至多2 ^ 16 = 65536的周期。由于65536均匀地划分3276800,您将看到周期性模式。

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.

这篇关于rand()函数在c ++中产生偶数和奇数,周期为3276800,谁知道为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆