libc random number generator flawed?

前端 未结 3 2150
清歌不尽
清歌不尽 2020-12-15 19:09

Consider an algorithm to test the probability that a certain number is picked from a set of N unique numbers after a specific number of tries (for example, with N=2, what\'s

3条回答
  •  无人及你
    2020-12-15 19:16

    As others pointed out, random() is not random enough.

    Using the higher bits instead of the lower ones does not help in this case. According to the manual (man 3 rand), old implementations of rand() had a problem in the lower bits. That's why random() is recommended instead. Though, the current implementation of rand() uses the same generator as random().

    I tried the recommended correct use of the old rand():

    if ((int)(rand()/(RAND_MAX+1.0)*36)==0)
    

    ...and got the same deep ditch at X=31

    Interstingly, if I mix rand()'s numbers with another sequence, I get rid of the ditch:

    unsigned x=0;
    //...
    
            x = (179*x + 79) % 997;
            if(((rand()+x)%36)==0)
    

    I am using an old Linear Congruential Generator. I chose 79, 179 and 997 at random from a primes table. This should generate a repeating sequence of length 997.

    That said, this trick probably introduced some non-randomness, some footprint... The resulting mixed sequence will surely fail other statistical tests. x never takes the same value in consecutive iterations. Indeed, it takes exactly 997 iterations to repeat every value.

    ''[..] random numbers should not be generated with a method chosen at random. Some theory should be used." (D.E.Knuth, "The Art of Computer Programming", vol.2)

    For simulations, if you want to be sure, use the Mersenne Twister

提交回复
热议问题