Reputation: 11
I have a simple code in C and there is a random number generation code in the middle.. problem is that for a long period of time that number stays the same and then goes one up! rand_pick might be 5 for over 30 times you run the C program and then will change finally to 6,... I wanted to know why and if there is another way to produce a really random 1 to 9 digit.
int rand_pick;
srand (time(NULL));
rand_pick = 1 + (int) (9.0*rand()/(RAND_MAX+1.0));
Thanks a lot ;)
Upvotes: 0
Views: 1393
Reputation: 4144
No, numbers should be quasi random. You can run this snippet of code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define RANDOM_COUNT 10000
int main(void) {
int rand_count[10] = {};
int rand_pick;
int i;
srand (time(NULL));
// run number of experiments
for(i = 0; i < RANDOM_COUNT; i++) {
rand_pick = 1 + (int) (9.0*rand()/(RAND_MAX+1.0));
rand_count[rand_pick]++;
}
for(i = 1; i <= 9; i++) {
printf("%d => %.3f %%\n", i, rand_count[rand_pick] /((float) RANDOM_COUNT));
}
}
It will randomly pick 10,000 numbers and count their distribution. I always get uniform distribution:
1 => 0.111 %
2 => 0.111 %
3 => 0.111 %
4 => 0.111 %
5 => 0.111 %
6 => 0.111 %
7 => 0.111 %
8 => 0.111 %
9 => 0.111 %
Upvotes: 2
Reputation: 28362
You only want to initialize srand once in your program. If you are running the program several times a second for some reason then you need to get a random number from somewhere else (like /dev/random on linux) to seed your random number generator.
Upvotes: 1