Xref: news2.mv.net comp.os.msdos.djgpp:8237 From: elric AT wheel DOT dcn DOT davis DOT ca DOT us (Jeffrey Taylor) Newsgroups: comp.os.msdos.djgpp Subject: Re: random() and rand() question Date: 3 Sep 1996 21:56:41 GMT Organization: Davis Community Network - Davis, California, USA Lines: 49 Message-ID: <50i9ip$qv5@mark.ucdavis.edu> References: <3225ABDD DOT 7AF48E03 AT alcyone DOT com> <507p1f$36f AT epx DOT cis DOT umn DOT edu> NNTP-Posting-Host: wheel.dcn.davis.ca.us To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Jason Hoffoss (hoffo002 AT gold DOT tc DOT umn DOT edu) wrote: : will work good, and give you good numbers. If you want like a number : from 1 to 100, however, doing random() % 100 + 1 isn't going to give : you great results. Why? Lets look at the natural range of random(). : It's a number from 0 to 4294967296. As you can see, with a %100, your : chances of getting a number from 0-95 is a little higher than your : chances of a number from 96-99. Other mod values will give you : different distributions. What I would recommend instead is something : like so, which keeps the probability flat: : : int myrand(void) : { : int n; : : do : { : n = random() & 127; : } while (n >= 100); : : return n; : } : : This gets quite a bit more complex when you want to generalize it for : any range, but this should point you in the right direction. If you : can, limiting your ranges to powers of 2 is the best solution. : : -Jason : Here is another solution. IF meory serves, it comes from RC4 author. // returns a random integer in range 0 <= X < sides unsigned range(unsigned sides) { unsigned const div = ((unsigned)RAND_MAX+1) / sides; unsigned result; while ((result = rand() / div) == sides) ; // retry return result; } -- ============================================ Without my guitar, I am a poet without arms. - Michael Bloomfield ============================================