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: 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> <5fps67$pc3 AT news DOT ox DOT ac DOT uk> Date: Sun, 9 Mar 1997 21:08:12 GMT Lines: 38 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp George Foot 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