Mail Archives: djgpp/1997/03/10/02:47:09
George Foot <gfoot AT mc31 DOT merton DOT ox DOT ac DOT uk> wrote:
>Dave Cigna (cigna AT helios DOT phy DOT OhioU DOT Edu) wrote:
>
>Admittedly, using '%' with a number which is not a power of two will
>give slightly more low numbers than high, but...
>
>: 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.
>
>... this is no better. For example, suppose that MAXINT were 4, and you
>set X to be 3. Then n would be one of {0.0,0.75,1.5,2.25}, and when cast
>to int this becomes {0,0,1,2} which is the same result as random()%3.
Yes, you're right. After thinking about it more carefully I realize
that there will always be (RAND_MAX % X) values that are favored.
>This is getting pedantic, but you cannot (simply) get a truly random
>distribution over X numbers from a random function returning one of
>2^n numbers. I say simply; one solution is to keep taking random() until
>the value is in the range you want. A more efficient technique is to keep
>taking random()&Y until it is in the required range, with Y=2^n-1 such
>that Y>=X-1.
>
>In practise, though, MAXINT and RAND_MAX are so high that it doesn't
>really matter.
Well, whether on not it's pedantic depends on what you're using the
numbers for. There are applications (for example Monte Carlo type
calculations) where non-uniformity of even this magnitude is a real
problem. But anyone using rand() or random() for this sort of thing
deserves what they get. So you are right, in practise it doesn't really
matter.
-- Dave Cigna
- Raw text -