cjones@isis.cs.du.edu (Charles J. Jones) (03/26/91)
I don't know if this has been covered before, but... There is a bug in the random function of Turbo C++ version 1.00. ^^^^ int random(int n); The command is supposed to return a value bewteen 0 and n-1, but instead it returns valus in the range 0..n. The nth values occursa with a frequency of 1 in 32767. The fix is easy since random is a macro based on rand. Look in your stdlib.h file for the random macro, note that it is something like this: #define random(n) (((long) rand() * n) / RAND_MAX)) The problem is that rand returns a value between 0 and RAND_MAX, RAND_MAX being 32767. If it does return RAND_MAX, then you get back the value you passed in! Okay, so change the above to read: #define random(n) (((long) rand()*n)/((long) RAND_MAX + 1)) which will ensure that you will never get back what you passed in. Note also that there are two macros here, one for C and another for C++. The C++ macro is an inline function and requires the same change. I performed a simple 1,000,000 iteration test on this fix to ensure that I hadn't screwed anything up and it produced a nice even distribution. Charles -- ============================================================= Charles J. Jones | Insert witty saying here. cjones@nyx.cs.du.edu |
theall@rm105serve.sas.upenn.edu (George A. Theall) (03/26/91)
In article <1991Mar26.000533.12013@isis.cs.du.edu> cjones@isis.UUCP (Charles J. Jones) writes: >There is a bug in the random function of Turbo C++ version 1.00. ... >The fix is easy ... >#define random(n) (((long) rand()*n)/((long) RAND_MAX + 1)) It's been fixed by Borland as of TC++ v1.01. George --- theall@rm105serve.sas.upenn.edu Dept. of Economics theall@ssctemp.sas.upenn.edu Univ. of Pennsylvania gtheall@penndrls.upenn.edu Philadelphia, PA 19104