开发者

Is rand() predictable in C++ [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What’s the Right Way to use the rand() Function in C++?

When I run the below program I always get the same values each time. Is rand not a true random function?

int main()
{

 while(1)
 开发者_Go百科{
 getch();
 cout<<rand()<<endl;
 }

}

In each run I am getting the below values.

41

18467

6334

26500

19169

15724

......


Yes and no. rand() is a pseudo random number generator that will always return the same sequence of numbers given the same seed value. Typically one 'seeds' the random number generator with some random data and then uses rand() to return a sequence of seemingly random numbers. If your random data isn't needed for something requiring 'true' randomness (such as cryptography based security) just using the current system time is sufficient. However, if you are using it for security purposes, look into obtaining more truly random data from entropy gathering utilities and use that to seed the random number generator.

As aa mentioned, the seed function is referenced here


What is a true random function? Last I checked, computers couldn't do that :)

As to why you are getting the same set of numbers each time, it's because you need to seed the built in number generator with some starting 'random' value. There are many places to get this, but some tend to look good, but turn out bad. In our games, we generally seed with tic time from game bootup until the first or second user input. User input will always vary across many tics and can therefore be used as a decent starting point.


If you are using a Microsoft compiler, you can use rand_s, which generates very good random numbers (as good as you can get with only a computer): http://msdn.microsoft.com/en-us/library/sxtz2fa8%28VS.80%29.aspx

You can also use /dev/urandom on Linux and CryptGenRandom() on Windows to get quality random numbers.


or put srand() at the beginning of the function.


Just to follow on from the disucussion on "True" random numbers. As already, stated any generator that has a seed has a predictable period - I believe it can be 2^48.

If that level of randomness you can use the following:

long randomLong(unsigned int x) 
{
    x ^= (x << 21); // x is a non zero seed value
    x ^= (x >> 35);
    x ^= (x << 4);
    return x;
}

This is taken from the following paper: http://www.jstatsoft.org/v08/i14/paper

Which is a really interesting paper describing some low cost random number generators

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜