rand() function in C is not random even when seeded

后端 未结 2 1323
星月不相逢
星月不相逢 2020-12-11 06:37

This is most likely a machine dependent issue but I can\'t figure out what could be wrong.

#include 
#include 
#include 

        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 07:43

    This is exactly what you should expect. There's no such thing as "a random number". There are only sequences of numbers with a random distribution. The rand() function generates such sequences, but you're not giving it a chance to, because you keep re-seeding it. The first number generated by rand() may very well be just some function of the seed, or the seed itself. Some rand() functions might hash the seed to hide this, but that doesn't really make them any better, because the contract of rand() is to produce a random sequence.

    If you need a sequence of random numbers that survives running multiple programs, you'll have to do something like (a) Write a program that calls srand() once, then calls rand() many times, and have your other programs ask for random numbers from that program over IPC; (b) Use something like /dev/urandom; (c) Use something like random.org.

提交回复
热议问题