Mail Archives: djgpp/1996/08/30/23:34:04
Erik Max Francis <max AT alcyone DOT com> wrote:
>J.J. Pierson wrote:
>> Silly question... How would I go about getting a random number from say 1
>> to a specified number?
>For a number between 1 and n, use 
>    rand()%n + 1.
>If n is an even power of 2, then bitwise-anding a mask will be faste:
>    rand()&(n - 1) + 1.
Ok, yes these will work, but they are not very good all the time.  I
would avoid using % if you want good random numbers.  If the range you
want is a power of 2, like 0-1, 0-7, 1-32, etc, then doing something
like:
   n = random() & 7;   or   n = random() & 31 + 1;
will work good, and give you good numbers.  If you want like a number
from 1 to 100, however, doing random() % 100 + 1 isn't going to give
you great results.  Why?  Lets look at the natural range of random().
It's a number from 0 to 4294967296.  As you can see, with a %100, your
chances of getting a number from 0-95 is a little higher than your
chances of a number from 96-99.  Other mod values will give you
different distributions.  What I would recommend instead is something
like so, which keeps the probability flat:
int myrand(void)
{
   int n;
   do
   {
      n = random() & 127;
   } while (n >= 100);
   return n;
}
This gets quite a bit more complex when you want to generalize it for
any range, but this should point you in the right direction.  If you
can, limiting your ranges to powers of 2 is the best solution.
    -Jason
+------------------------------------------------------ -  -   -    -     -
---------------- Jason Hoffoss, author of DMapEdit
-------- Email: hoffo002 AT gold DOT tc DOT umn DOT edu
--- Homepage: http://www.umn.edu/nlhome/g253/hoffo002
- DMapEdit: http://www.umn.edu/nlhome/g253/hoffo002/dmapedit
- Raw text -