Article View: comp.os.msdos.programmer
Article #5436TC++ 1.00 Bug in random(int)
From: Charles J. Jones
Date: Tue, 26 Mar 1991 00:05
Date: Tue, 26 Mar 1991 00:05
35 lines
1786 bytes
1786 bytes
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 |
Technical Details
Message-ID:
<1991Mar26.000533.12013@isis.cs.du.edu>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!cs.utexas.edu!uunet!isis!cjonesShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!cs.utexas.edu!uunet!isis!cjones From: cjones@isis.cs.du.edu (Charles J. Jones) Newsgroups: comp.os.msdos.programmer Subject: TC++ 1.00 Bug in random(int) Summary: easy to fiX Message-ID: <1991Mar26.000533.12013@isis.cs.du.edu> Date: 26 Mar 91 00:05:33 GMT Reply-To: cjones@isis.UUCP (Charles J. Jones) Organization: Math/CS, University of Denver Lines: 35