random() error in Turbo C++
Karl Heuer
karl at haddock.ima.isc.com
Sat Sep 1 08:25:27 AEST 1990
In article <118662 at linus.mitre.org> jrv at 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 <stdlib.h>
int random(int n) {
register int r;
do r = rand() / ((RAND_MAX + 1UL) / n); while (r >= n);
return (r);
}
Karl W. Z. Heuer (karl at kelp.ima.isc.com or ima!kelp!karl), The Walking Lint
More information about the Comp.lang.c
mailing list