Homerun?
Problem 7What
can you infer about the rand() function after looking at the code
and its output?
#define ITER 10000
#define SEED 0x12345678
test()
{
int i;
int counts[4]={0,0,0,0};
srand(SEED);
for (i=0; i4; i++)
{
printf("%d bin probability = %f\n", i, counts[0]/(float)ITER;
}
}
After running the code many times with different values for ITER
and SEED, you always get the same output:
0 bin probability = 0.25000
1 bin probability = 0.25000
2 bin probability = 0.25000
3 bin probability = 0.25000
Answer:
If ITER and SEED remained constant, you would expect to get identical
results every time. But given that the SEED is changed you would expect
to get different results. If you were to flip a coin a 100 times and
got exactly 50 heads and 50 tails, you might think it a little coincidental.
But to repeat the experiment again and again without variation can
only mean one thing -- it is not random.
In this case, only the two lowest order bits of the random number
were being used. Some C compilers use random number generators that
do not produce random numbers in all of their bits.
8-99
|