Path: utzoo!utgpu!news-server.csri.toronto.edu!mailrus!uwm.edu!cs.utexas.edu!samsung!usc!snorkelwacker!husc6!spdcc!ima!haddock!karl From: karl@haddock.ima.isc.com (Karl Heuer) Newsgroups: comp.lang.c Subject: Re: random() error in Turbo C++ Message-ID: <17607@haddock.ima.isc.com> Date: 31 Aug 90 22:25:27 GMT References: <118662@linus.mitre.org> Reply-To: karl@kelp.ima.isc.com (Karl Heuer) Organization: Interactive Systems, Cambridge, MA 02138-5302 Lines: 16 In article <118662@linus.mitre.org> jrv@sdimax2.mitre.org (VanZandt) writes: > #define random(n) ((int)((long)rand()*(n))/((long)RAND_MAX+1)) >p.s. Note that the common device of using rand()%n is guaranteed to >yield a number in the range 0...n-1, but the probabilities are not uniform. This is equally true of your version (proof: there are RAND_MAX+1 equally likely outcomes but n possible results); only the particular "hot" values have been redistributed. If it's important, here is a correct algorithm. #include int random(int n) { register int r; do r = rand() / ((RAND_MAX + 1UL) / n); while (r >= n); return (r); } Karl W. Z. Heuer (karl@kelp.ima.isc.com or ima!kelp!karl), The Walking Lint