使用非随机的qsrand随机方法 [英] Use of qsrand, random method that is not random

查看:103
本文介绍了使用非随机的qsrand随机方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到一个奇怪的问题,我无法设法找到一个很好的解释,所以我想到要问你们:

I'm having a strange problem here, and I can't manage to find a good explanation to it, so I thought of asking you guys :

请考虑以下方法:

int MathUtility::randomize(int Min, int Max)
{
    qsrand(QTime::currentTime().msec());

    if (Min > Max)
    {
        int Temp = Min;
        Min = Max;
        Max = Temp;
    }
    return ((rand()%(Max-Min+1))+Min);
}

我不会向您解释大师这种方法的实际作用,我将解释我的问题:

I won't explain you gurus what this method actually does, I'll instead explain my problem :

我意识到,当我在循环中有时调用此方法时,会一遍又一遍地得到相同的随机数...例如,此代码段...

I realised that when I call this method in a loop, sometimes, I get the same random number over and over again... For example, this snippet...

for(int i=0; i<10; ++i)
{
    int Index = MathUtility::randomize(0, 1000);
    qDebug() << Index;
}

...将产生类似:

567 567 567 567 ...等...

567 567 567 567...etc...

我也意识到,如果我不是每次都调用qsrand,而是在应用程序的生命周期中仅调用一次,它就可以正常工作...

I realised too, that if I don't call qsrand everytime, but only once during my application's lifetime, it's working perfectly...

我的问题:为什么?

推荐答案

因为如果您在一毫秒内多次调用randomize(这很可能在当前的CPU时钟速度下),则您将RNG植入相同的种子价值. 保证从RNG产生相同的输出.

Because if you call randomize more than once in a millisecond (which is rather likely at current CPU clock speeds), you are seeding the RNG with the same value. This is guaranteed to produce the same output from the RNG.

随机数生成器只能播种一次.将它们多播种并不会使输出变得更加随机,实际上(如您所发现的)可能会使输出变得随机.

Random-number generators are only meant to be seeded once. Seeding them multiple times does not make the output extra random, and in fact (as you found) may make it much less random.

这篇关于使用非随机的qsrand随机方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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