delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/03/24/16:55:38

From: Jason Alexander <jalex AT ea DOT oac DOT uci DOT edu>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Random integers
Date: Tue, 24 Mar 1998 12:00:26 -0800
Organization: University of California, Irvine
Lines: 27
Message-ID: <351810D9.47E35207@ea.oac.uci.edu>
References: <01bd5744$ee33b280$LocalHost AT PIETER>
NNTP-Posting-Host: pv1821.pv.reshsg.uci.edu
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Erik Max Francis wrote:

>Use
>
>   rand()%n + 1
>
>which will give you a random number betwen 1 and n, inclusive.
>
>Note that pseudorandom number generators tend to be poor in their lower
>significant bits, so this is sometimes not an ideal solution.

  I believe one could easily get around this by bitshifting the result of rand()
to move the high-order bits so that the mod operation uses them.  First, figure
out how many bits are needed to represent the number n (call this N) and then
use

 ((rand() >> (32-N)) % n) + 1

I haven't tested this, but either it (or something very similar to it) should
work, right?  Of course, if the random numbers will be called many times, 32-N
should be replaced by the actual value to avoid the arithmetic operation each
time the random number generator is called.  (Maybe the gcc optimizer does this
already... I don't know)

Jason


- Raw text -


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