www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/08/30/23:34:04

Xref: news2.mv.net comp.os.msdos.djgpp:8086
From: hoffo002 AT gold DOT tc DOT umn DOT edu (Jason Hoffoss)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: random() and rand() question
Date: Sat, 31 Aug 1996 00:14:09 GMT
Organization: University of Minnesota
Lines: 55
Message-ID: <507p1f$36f@epx.cis.umn.edu>
References: <DwvF3A DOT H2r AT interactive DOT net> <3225ABDD DOT 7AF48E03 AT alcyone DOT com>
NNTP-Posting-Host: dialup-1-49.gw.umn.edu
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019