Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   pass time(0) to srand() when generating random numbers. (http://www.velocityreviews.com/forums/t316010-pass-time-0-to-srand-when-generating-random-numbers.html)

Intaek LIM 10-31-2003 08:45 AM

pass time(0) to srand() when generating random numbers.
 
generally, we use srand(time(0)) to generate random numbers.
i know why we use time(0), but i can not explain how it operates.

first, see example source below.

---------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
printf("This will generate 5 random numbers.\n\n");

srand(time(0));

int i;
for(i=0; i<5; i++)
{
printf("generated %d\n", rand());
}

return 0;
}
---------------------------------------------

this is an idiom of generating random numbers, i think.
and a different source below operates correctly too.

---------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
printf("This will generate 5 random numbers.\n\n");

int seed = time(0);
srand(seed);

int i;
for(i=0; i<5; i++)
{
printf("generated %d\n", rand());
}

return 0;
}
---------------------------------------------

but, following source produces incorrect results.
(returns the same values everytime)


---------------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
printf("This will generate 5 random numbers.\n\n");

// seed is the return value for time(0)
// i wrote it by my hand. :-(
int seed = 1067589554;
srand(seed);

int i;
for(i=0; i<5; i++)
{
printf("generated %d\n", rand());
}

return 0;
}
---------------------------------------------

what is the difference of these three sources?
plz tell me something who knows it.

Andreas Kahari 10-31-2003 09:02 AM

Re: pass time(0) to srand() when generating random numbers.
 
In article <d93e2a33.0310310045.575d3fb9@posting.google.com >, Intaek LIM wrote:
[cut]
> // seed is the return value for time(0)
> // i wrote it by my hand. :-(
> int seed = 1067589554;
> srand(seed);


The time() function returns a value that represents the current
time. Seeding the pseudo random generator with time(0) will
ensures that you get a different pseudo random list of numbers
each time you run the program.

Hard coding the seed ("1067589554" in your code) ensures that
you get the *same* pseudo random list of numbers each time you
run your program.

--
Andreas Kähäri


All times are GMT. The time now is 07:17 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.