delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/07/30/01:57:07

Message-ID: <37A0B899.56CC82A3@lycosmail.com>
Date: Thu, 29 Jul 1999 16:24:57 -0400
From: Adam Schrotenboer <ajschrotenboer AT lycosmail DOT com>
X-Mailer: Mozilla 4.6 [en] (Win98; U)
X-Accept-Language: en
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re: -- Random question --
References: <7nd0vu$igt$1 AT zingo DOT tninet DOT se> <7nd9so$a96 AT dfw-ixnews3 DOT ix DOT netcom DOT com> <379A42F1 DOT AF23A6DF AT vetec DOT com>
Reply-To: djgpp AT delorie DOT com

Andy Goth wrote:

> > You can use the remainder operator like this:
> >
> > number = (rand() % 101) + 1;
>
> The rand() % 101 part will return a number from 0 to 100, so if you add
> one to that you get 1 to 101.  Try (rand() % 100) + 1 instead (1 to
> 100).
>
> > This will generate a number from 1 to 100. You can also substitute rand()
> > with random() which generates numbers that are more random, but random()
> > isn't as portable. Don't forget to seed it at the start of your program like
> > this:
> >
> > srand(time(0)); /* for rand() */
> > srandom(time(0)); /* for random() */

Although I agree that your method works, I also remember it earlier (months ago)
being said that the lower bits are not considered very random, and a better way is
to do something like this

number = (int)(rand() / RAND_MAX)*100+1;

or a more general formula (different for ints than floats)

for an int
int number = (int)((rand()/RAND_MAX)*(high - low + 1));

for a float
int number = (float)((rand()/RAND_MAX)*(high - low));

The above are taken from a working piece of code that utilizes a long sequence
random number generator. I have tested it before to verify that it does not go out
of bounds, simple compound if statement. Never tested it for randomness however.

Also, to correct your correction, the docs say for a range 0..N, use rand()%(n+1),
so (rand()%101)+1 is half right, just remove the +1, but keep the 101.

- Raw text -


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