+     ulowell!MathWorks.Com!!!cme
From: (Carl Ellison)
Newsgroups: sci.crypt

Subject: Re: modran(x)
Date: 24 Feb 1994 21:01:16 GMT
Organization: Stratus Computer, Marlboro MA
Lines: 27
Distribution: world
Message-ID: <2kj4is$>
References: <>

In article <> (Keith W illis) writes:
>        In the sci.crypt FAQ, section 8.13, it says that a modran(x)
>        function which returns "a uniformly distributed random integer
>        in the interval [0..x-1]" cannot be achieved by a simple
>        (ranno() % x).  What exactly is the problem with this
>        approach?  
>        More generally, given the standard system function rand()
>        which returns numbers in the range 0 to RAND_MAX, what is the
>        correct method for arriving at numbers in the range 0 to N? 

For example, if ranno() were to return a number in the range 0..14 and x
were 10, then (ranno() % x) would produce an element in [0..4] twice as
often as an element in [5..9].  So, the distribution is not uniform.

What you can do is compute (RAND_MAX % x) and if the raw value from ranno()
is <= that value, toss it and ask for a new ranno().

 - Carl
 Carl M. Ellison                           
 RIPEM MD5OfPublicKey: 39D9860686A9F075A9A83D49589C677A
 Stratus Computer Inc.                               TEL: (508)460-2783
 55 Fairbanks Boulevard ; Marlborough MA 01752-1298  FAX: (508)624-7488