C ++可预测的Rand()输出 [英] C++ Predictable Rand() Output

查看:136
本文介绍了C ++可预测的Rand()输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在注意到rand()函数每次产生相同的输出41之后,我使用srand(time(0))为生成器设置了种子.这解决了重复输出的问题,但现在它使我的人数不断增加. (即245、248、250、253、255、256).我可以理解,由于受系统时间的影响,这种情况正在增加,但这是正常现象吗?

After noticing that the rand() function produced the same output of 41 each time, I seeded the generator using srand(time(0)). That solved the problem of the recurring output but now it's giving me constantly increasing numbers. (I.E. 245, 248, 250, 253, 255, 256). I can understand that it is increasing because of the influence by the system time but is this normal?

这是我的程序:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{

    int number;

    srand(time(0));

    cout << rand() % 1000;

    return 0;

}

我正在反复运行此程序,而不是循环运行. 多次试验的结果: 285 295 305 311 325 334 344 354 355

I am running this repeatedly and not in a loop. Outputs of multiple trials: 285 295 305 311 325 334 344 354 355

推荐答案

C ++ C ++ rand()使用最简单的随机生成器

C++ rand() from MS uses the simplest random generator Linear congruential generator

这是它的代码:

int __cdecl rand (
    void
    )
{
    _ptiddata ptd = _getptd();

    return( ((ptd->_holdrand = ptd->_holdrand * 214013L
        + 2531011L) >> 16) & 0x7fff );
}

因此,每当您为函数添加种子时,您只需设置第一个值(如果您快速运行程序,该值显然会不时地增加一些单位)

So whenever you seed your function you just set the first value (which obviously increases just by some units from time to time if you run your program fast)

现在,如果插入rand()的数学方程式,则值为x+a,其中x是上次调用函数所使用的值,而a是自调用以来的时间变化量将注意: ((x + a)* 214013 + 2531011)>> 16 =(x * 214013 + 2531011 + a * 214013)>> 16

Now if you plug in your math equation of the rand() a value x+a where x is the value with which your function was called last time and a is the variation of your time since that call you will notice: ((x+a) * 214013 + 2531011) >> 16 = (x*214013+2531011 + a*214013) >> 16

由于运行程序非常快.可以说,您的a05秒之间变化.然后,您的a*214013的最大值为1070065,当您将该数字右移16位时,最后以十进制的16结尾,这是大约,您的新输出与您上一个(我之所以说是因为您不能说(x * 214013 + 2531011 + a * 214013)>> 16 =(x * 214013 + 2531011 >> 16)+(a * 214013 >> 16)携带)

Since you run your program very fast. Your a varies between 0 and 5 sec let's say. Then your a*214013 has a max value of 1070065 now when you right shift this number by 16 bits you end up with 16 in decimal and this is approximately how much your new output differs from your previous one (I say approximately because you can not say that (x*214013+2531011 + a*214013) >> 16 = (x*214013+2531011 >> 16) + (a*214013 >> 16) because of the carries)

这篇关于C ++可预测的Rand()输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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