C++ Predictable Rand() Output

前端 未结 6 432
陌清茗
陌清茗 2021-01-14 14:57

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 outpu

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-14 15:12

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

    This is the code for it:

    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)

    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

    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)

提交回复
热议问题