www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/03/07/16:03:41

Newsgroups: comp.os.msdos.djgpp
From: cigna AT helios DOT phy DOT OhioU DOT Edu (Dave Cigna)
Subject: Re: a randomize function for DJGPP?
Message-ID: <E6oqJs.K2n@boss.cs.ohiou.edu>
Sender: news AT boss DOT cs DOT ohiou DOT edu (News Admin)
Organization: Ohio University Physics and Astronomy
References: <5flbpp$m74 AT nr1 DOT ottawa DOT istar DOT net> <331FC0D1 DOT 1A26 AT cs DOT com>
Date: Fri, 7 Mar 1997 18:11:52 GMT
Lines: 29
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

John M. Aldrich <fighteer AT cs DOT com> wrote:
>
>To get a random number from 0 to X - 1, use:
>
>    n = random( ) % X;
>
>Before everybody gets hysterical on me again, let me say in advance that
>the GNU random() RNG, unlike rand(), is guaranteed to be random in the
>lower bits, so you can use the mod operator safely.

The numbers will still not be uniformly distributed. Smaller values are
more likely than large ones. To understand why, remember that random()
and rand() return an integer between 0 and RAND_MAX. Suppose, just for
the sake of argument, that RAND_MAX == 5 and you want random numbers
from 0 to 3. Then random()%4 will evaluate to 1 when random() returns
*either* 1 or 5, but the only way to get a 3 is for random() to return
exactly 3. In other words 0 and 1 are twice as likely to occur as 2 and 
3 in this case. Even with a large RAND_MAX (like 2^31), the numbers at
the small end of (0,X) will be more likely than those at the high end.

The best way to get get random numbers uniformly distributed from
0 to X-1 is to use:

  n = ((double)random() / RAND_MAX) * X;

If you want to cast n to an int, that's your business.

 -- Dave Cigna

- Raw text -


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