了解Visual C ++ rand()函数的算法 [英] Understanding the algorithm of Visual C++'s rand() function

查看:89
本文介绍了了解Visual C ++ rand()函数的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C/C ++中,当我们想要获取随机整数时,通常使用rand()srand().但是当我尝试自己重写它时,我发现很难理解该算法.只需几行就可以很容易地编写该函数,但是公式存在误解.

In C/C++, rand() and srand() are usually used by us when we want to get a random integer. But when I tried to rewrite it myself, I found it difficult to understand the algorithm. The function is very easily written in only a few lines, but the formula is misunderstanding.

主要公式:

ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L;

涉及的原始代码:

void __cdecl srand (unsigned int seed)
{
    _getptd()->_holdrand = (unsigned long)seed;
}

int __cdecl rand (void)
{
    _ptiddata ptd = _getptd();
    return ( ((ptd->_holdrand = ptd->_holdrand * 214013L + 2531011L) >> 16) & 0x7fff );
}

推荐答案

这只是模块化算法.您要乘以一个以2 ^ 32为模的数字,例如,然后将高16位作为随机"数字返回.由于您要对模数乘以互加的数字,因此会创建一种均匀分布的数字.

It's just modular arithmetic. You're multiplying and adding to a number which is taken modulo 2^32 (for example), and returning the upper 16 bit as your "random" number. Because you're multiplying and adding numbers which are coprime to the modulus, this creates sort of uniformly distributed numbers.

仔细选择两个数字非常重要.例如,如果您使用"* 4"和"+ 8",则可能不会遇到很多随机性.

The careful choice of the two numbers is very important. For example, if you had used "* 4" and "+ 8", you would probably not experience a lot of randomness.

此方案称为线性同余.

这篇关于了解Visual C ++ rand()函数的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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