# random number generation

• 06-26-2007
megastar
random number generation
These are two programs for generating random 0's and 1's
The essential logic is the same the first one
has the code in main whereas the second one has in the function
randgen().
The first is generating the correct output whereas the second is giving only zeroes.Why the discrepancy?
PROGRAM 1
Code:

```#include<stdio.h> #include<time.h> #include<stdlib.h> int main() { int i; time_t seconds; time(&seconds); srand((unsigned int)seconds); for(i=0;i<100;i++) { printf("%d",rand()%2); } }```

PROGRAM 2
Code:

```#include<stdio.h> #include<stdlib.h> #include<time.h> int randgen() { time_t seconds; time(&seconds); srand((unsigned int) seconds); return rand()%2; } int main() { int i=0; for(i=0;i<100;i++) printf("\n %d",randgen()); }```
• 06-26-2007
laserlight
You should seed the random number generator only once.

Incidentally, you could consider reading about using rand() and pseudorandom number generators in general.
• 06-26-2007
Salem
Well in the second one, you're calling srand() with a constant, so naturally rand() is always going to produce the same sequence.

Time might seem a fluid thing to you, but to the couple of mSec it takes this program to run (if that), it looks pretty close to being a constant.
• 06-26-2007
megastar
@
Code:

```laser light         Code:         You should seed the random number generator only once If i am not wrong the reason for manual seeding if i may call is to choose  'numbers of random sequence' i.e.  a different starting value in a sequence will lead to different set of numbers of the same sequence {a(n)}.So using 'time' which is constantly variable, i intended to generate different seeds in the second one case unlike the first one where the seed is a constant . So there is no hard and fast rule that seeding has to take place once.Please correct me if i am wrong. I think Salem's explanation of the discrepancy is correct wherein he points out that the  time is almost a constant resulting in the generation of same initial value every time.  Anyway both of you thanks for the links and explanations.```
• 06-26-2007
laserlight
If you were running some simulation repeatedly by seeding from a list of pre-determined seeds, then of course you would seed more than once. In this case, you are obtaining a seed in a rather raw form from time(), so you should seed only once. Even so, I would suggest using the suggestion of time_seed() from the eternallyconfuzzled.com link on using rand().