开发者

Mysterious random number - wanting to be the same even after "srand()" [duplicate]

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

Possible Duplicate:

Rand generating same numbers

The following is tried when answering another question on StackOverflow:

#include <time.h>
#include <iostream>

using namespace std;

main() {
  srand ( time(NULL) );
  cout << (float) rand() / RAND_MAX << endl;
  cout << ((float) rand())  << endl;
  cout << RAND_MAX << endl;
  cout << (float) rand() / RAND_MAX << endl;
}

Very strangely, the first output number is always a similar number, either on Windows 7 with cygwin or on Mac with Leopard.

The last number is a good random number from 0 to 1. If the first cout line is commented out, the first printed random number is always a similar value on开发者_C百科e.

How could that be happening?


I have stumbled upon this phenomenon myself in the past. The first call to rand() in four sequential runs of a test program gave the following output:

27592
27595
27598
27602

Notice how similar those numbers are? This is because the random number generator is initialized with the current time, and the first result is heavily influenced by that. Similar initial values for srand yield similar initial results for rand. It's as simple as that.

This similarity is irrelevant if you calculate rand() % n, but if you go with the rand() / m approach, this is a problem. For example, if you divide rand() by 100, you will get the same number 3 times in a row! Now let's take a look at the second result of rand() in four sequential runs:

11520
22268
248
10997

This looks much better, doesn't it? A simple quick-fix is to call rand() a few times after seeding and simply ignoring the result.

int main()
{
    srand(time(0));
    rand(); rand(); rand();

    std::cout << rand() / float(RAND_MAX) << std::endl;
}


rand() function in VS2008 returns this: return ((current_value = current_value * 214013 + 2531011) >> 16) & 0x7fff;. This current_value you set with srand. This function is such that it will return similar pseudo random numbers for similar seeds, and there is no help about it. The problem is that those bits that are the most random in first call are eaten up with >> 16 part. To workaround the problem just roll it a few times (rand(); rand();).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜