bli00
bli00

Reputation: 2787

C++ `srand()` function producing a pattern?

New to C++ and following the beginner's tutorial here. Refer to the section titled Random Numbers in C++. Using exactly the code given:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main () {
   int i,j;

   // set the seed
   srand( (unsigned)time( NULL ) );

   /* generate 10  random numbers. */
   for( i = 0; i < 10; i++ ) {
      // generate actual random number
      j = rand();
      cout <<" Random Number : " << j << endl;
   }

   return 0;
}

I'm seeding srand() with time() (compiled with g++) and so the generated result should be completely random. However, here's the result I'm getting:

$ ./a.out
 Random Number : 1028986599
 Random Number : 491960102
 Random Number : 561393364
 Random Number : 1442607477
 Random Number : 813491309
 Random Number : 1467533561
 Random Number : 986873932
 Random Number : 1373969343
 Random Number : 411091610
 Random Number : 761796871
$ ./a.out
 Random Number : 1029003406
 Random Number : 774435351
 Random Number : 36559790
 Random Number : 280067488
 Random Number : 1957600239
 Random Number : 1937744833
 Random Number : 1087901476
 Random Number : 684336574
 Random Number : 1869869533
 Random Number : 621550933
$ ./a.out
 Random Number : 1029020213
 Random Number : 1056910600
 Random Number : 1659209863
 Random Number : 1265011146
 Random Number : 954225522
 Random Number : 260472458
 Random Number : 1188929020
 Random Number : 2142187452
 Random Number : 1181163809
 Random Number : 481304995

As you can see from the first number generated on each ./a.out execution, the first number in the 10-loop is increasing on each execution. And it seems to always be about 1.02 million. Further testing suggests this pattern always holds and it's not a coincidence.

I can only assume that it's increasing due to the seed time(), which is always increasing. But that suggests the rand() function isn't truly random and is predictable.

Upvotes: 0

Views: 546

Answers (1)

David Schwartz
David Schwartz

Reputation: 182769

But that suggests the rand() function isn't truly random and is predictable.

Yes, that's absolutely correct. Typically, rand is implement with a very simple pseudo-random number generator. The use of rand is not appropriate when numbers that are truly random or unpredictable are required.

Under the hood, your implementation probably uses a Linear congruential generator and your three examples are all inside the same linear interval, at least for the first output.

Upvotes: 5

Related Questions