[gameprogrammer] Re: Random Integer Problem :(

Honestly I can't because I haven't read the books related. I haven't
the time to study the mathematics associated to the random number
generation right now. However, the basic idea is that a random number
generator is a suite of value that appears to be random because it has
the property to distributing homogeneously values among a range [O,
RANGE_MAX[. Using the modulo you do not map this range to your range
you simply shrink it.

In the second method you convert this random value to a float number
between 0 and 1 and then adapt this number to your range ensuring an
homogeneous mapping from the initial range to the final range.

I have made a program to gather some statistics on the appearance of
various value in the target range but the statistics does not really
highlight one method better than the other. I attached it for comments
and for you to evaluate by yourself.

If anyone has a better explanation (which is not going to be really
hard) or a better way to highlight the benefits of one method over the
other,  I would be really pleased to read of it here.


One last comment. You should not use srand before all call to rand. Just do it once. Or you can simply use time() % 6 to get your random value.




On 9/24/06, Andrew Falgout <andrew.falgout@xxxxxxxxx> wrote:
Perhaps you can explain why the modulus would be the improper way of getting
a random number?


On 9/24/06, Olivier Delannoy < olivier.delannoy@xxxxxxxxx> wrote: > > In Numerical Recipes in C: The Art of Scientific Computing (William H. > Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New > York: Cambridge University Press, 1992 (2nd ed., p. 277)), the follow- > ing comments are made: > > "If you want to generate a random integer between 1 and 10, you > should always do it by using high-order bits, as in > > j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0))); > > and never by anything resembling > > j = 1 + (rand() % 10); > > > from unix man page of rand > $> man 3 rand > > On 9/24/06, Chris Nystrom <cnystrom@xxxxxxxxx> wrote: > > > > > > On 9/23/06, Sahan Chandrasekara < sahanthegamecreator@xxxxxxxxx> wrote: > > > Hi, > > > > > > I'm trying to use this code to generate a random number between 1 and six > > inclusive: > > > > > > > > > int random_int() { > > > srand(time(NULL)); > > > int random_num=rand()%7; > > > return random_num; > > > } > > > > > > But it dosen't work. My program is programmed to quit immediantly if the > > number is not between 1 and six inclusive, and that is what it does > > > > I believe for 1-6 you want something like: > > > > random_num = ((rand() % 6) + 1); > > > > Chris > > > > -- > > E-Mail: Chris Nystrom <cnystrom@xxxxxxxxx > > > http://www.newio.org/ > > AIM: nystromchris > > > --------------------- > To unsubscribe go to http://gameprogrammer.com/mailinglist.html > > >



--
./Andrew

Other related posts: