ChipCenter Questlink
SEARCH CHIPCENTER
Search Type:
Search for:




Knowledge Centers
Product Reviews
Data Sheets
Guides & Experts
News
International
Ask Us
Circuit Cellar Online
App Notes
NetSeminars
Careers
Resources
FAQ
EE Times Network
Electronics Group Sites

Answer7


Circuit Cellar Online
THE MAGAZINE FOR COMPUTER APPLICATIONS
Circuit Cellar Online offers articles illustrating creative solutions
and unique applications through complete projects, practical
tutorials, and useful design techniques.

Archive

WHAT'S YOUR ENGINEERING QUOTIENT?

Test Your EQ•Homerun?

Problem 7—What 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


For questions or comments about
Test Your EQ, e-mail eq@circuitcellar.com
.
Click here to get your listing up.

Copyright © 2003 ChipCenter-QuestLink
About ChipCenter-Questlink  Contact Us  Privacy Statement   Advertising Information  FAQ