This code has generated a 1 result for r on the 1st toss 200 times in a row; the later tosses aren’t static; they change; any idea what I screwed up?? Using Xcode. Thanks!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define tprop .5 // propability coin will be tails
int main(int argc, const char *argv[])
{
int i; // for loop counter
int n; // # of rolls
int hc = 0; // heads counter
int tc = 0; // tails counter
int r; // roll... 1=heads, 0=tails
srand(time(NULL)); // seed Random# generator with current time
printf("Enter # of times to toss a coin: ");
scanf("%i", &n);
for (i = 0; i < n; i++) {
if ((float) rand() / RAND_MAX > tprop) {
r = 1;
hc++;
} else {
r = 0;
tc++;
}
printf("%in", r);
}
printf("# of times heads came up: %i (%f%%)n", hc, (float) hc / n * 100);
printf("# of times tails came up: %i (%f%%)n", tc, (float) tc / n * 100);
return 0;
}
To answer this question, first we need to look at rand() code.
From Rand Implementation:
As you can see, the random value is computed based on the seed value (and a new seed value is the computed), thats why we call those numbers pseudo-random. Since we are intersted in the first run, lets simplify the code a bit, lets write a function which takes the input the seed, and return the first rand():
And now lets run a test with with this function:
Here I got this result:
So, as you can see, if the seed are close, the values will probably be close to, and since you used the current time, the 200 tests you ran were all with seed values close to each other.
time(NULL) return the current time in seconds. To get better results you should use the time in milliseconds (and if you really need the values to change a lot between 2 runs do some operation over it).