www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/04/13/08:50:31

From: Erik Max Francis <max AT alcyone DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Help! Random is not working right
Date: Sun, 13 Apr 1997 01:43:36 -0700
Organization: Alcyone Systems
Lines: 28
Message-ID: <33509CB8.EFFF98A@alcyone.com>
References: <3349B612 DOT 68C AT ucsu DOT Colorado DOT edu> <860484279 DOT 79294 AT red DOT parallax DOT co DOT uk>
NNTP-Posting-Host: newton.alcyone.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

John Eccleston wrote:

> Rather than using the AND operator use the MODULUS operatorinstead, so
> 
>    random() & 9
> 
> becomes
> 
>    random() % 10
> 
> This will return values between 0 and 9.
> 
> Using the AND operator as you have done simply returns the bits set
> in the value returned by random and those set in 9 ie (1001),  which
> is why you only see the extremes of your value range.

It should be noted for people who are wondering why they've seen masks
used this way is that masking is equivalent to a modulus operation (and
much faster) when the modulo (one greater than the mask) is an even power
of two.

-- 
       Erik Max Francis, &tSftDotIotE / email / max AT alcyone DOT com
                     Alcyone Systems /   web / http://www.alcyone.com/max/
San Jose, California, United States /  icbm / 37 20 07 N  121 53 38 W
                                   \
                      "The future / is right there."
                                 / Bill Moyers

- Raw text -


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