Path: utzoo!utgpu!watserv1!watmath!att!pacbell!pacbell.com!ucsd!usc!samsung!think.com!linus!linus!sdimax2.mitre.org From: jrv@sdimax2.mitre.org (VanZandt) Newsgroups: comp.lang.c Subject: random() error in Turbo C++ Message-ID: <118662@linus.mitre.org> Date: 30 Aug 90 14:41:07 GMT Sender: usenet@linus.mitre.org Organization: The MITRE Corp., Bedford, MA Lines: 21 random() in Turbo C is supposed to return a random integer in the range 0...n-1. Actually, it will occasionally (once in 32768 calls) return n. random() is implemented by a macro #define random(n) ((int)((long)rand()*(n))/RAND_MAX) However, when rand() returns RAND_MAX (which is 32767), this evaluates to n. To correct this, increment RAND_MAX (noting that it must thereby become a long): #define random(n) ((int)((long)rand()*(n))/((long)RAND_MAX+1)) - Jim Van Zandt (jrv@mbunix.mitre.org) 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. For n=30000, the probability of getting 9 is twice the probability of getting 29000.