"John Harrison" <jo*************@hotmail.com> wrote in message news:<2g************@uni-berlin.de>...
[ ... ]
The C FAQ has a section on generating random numbers.
http://www.eskimo.com/~scs/C-faq/s13.html questions 13.15 to 13.20. 13.16
and 13.17 explain why your teachers function is poor.
The "solutions" presented in the FAQ provide little improvement.
If rand() is at all competently written, several of the least
significant bits have already been eliminated, so there's little real
difference between using % and using / to clamp the output to a range.
Unfortunately, both result in biased results except when RAND_MAX
happens to be an even multiple of the range you're asking for. In the
common case that RAND_MAX is a prime number, that's a pretty rare
occurrence...
Code like this can produce unbiased results:
int rand_lim(int limit) {
/* return a random number between 0 and limit inclusive.
*/
int divisor = RAND_MAX/(limit+1);
int retval;
do {
retval = rand() / divisor;
} while (retval > limit);
return retval;
}
--
Later,
Jerry.
The universe is a figment of its own imagination.