Generating same random numbers...

Nov 28, 2011 at 1:40pm
Hi all,

I have been trying to figure out this matter for hours. I have a code that generates random numbers. Regardless of how many times i compiled and run, i still get the same random numbers. Anyone care to explain?

1
2
3
4
5
6
int a;
for (int i=0; i < 5; i++)
{
   a = rand();
   cout << a << endl;
}



1804289383
846930886
1681692777
1714636915
1957747793
Nov 28, 2011 at 1:44pm
C++'s built-in RNG doesn't seed itself. ("What's a seed?" Well, it's impossible for a computer to generate a random number without random input. It requires (a) seed(s) to randomize.)

You can manually seed the RNG using srand(uint). http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

It's quite custom to use the current time as a seed. With sufficient precision on your time() function, it's pretty random. The link uses time in its example, so might as well just copypaste!

(P.S.: It's often very handy to use a constant to seed your RNG. That way, you can mimic a random without stochasticity if, for example, you need to compare outcomes of several runtimes.)
Last edited on Nov 28, 2011 at 1:44pm
Nov 28, 2011 at 1:47pm
Because the numbers that are being called, all start at the same place in memory. To get different values, you have to seed the rand function.The best way is to #include <time.h> , then at the top of your program, after main(),
1
2
 time_t t;
srand((unsigned) time(&t));
. You will get a different set of numbers each time you run your program.
Nov 28, 2011 at 2:02pm
Thank you Gaminic & whitenite1! I am enlightened now. Thanks for the help rendered!
Topic archived. No new replies allowed.