rand()

  • Thread starter Thread starter Bill Burris
  • Start date Start date
B

Bill Burris

Hi,

With VS .NET 2003 the rand() function sometimes returns a number equal to
RAND_MAX. The docs say: The rand function returns a pseudorandom integer in
the range 0 to RAND_MAX. Does this mean that 0 & RAND_MAX are included in
the range?

I am asking because I was using code from a book, which was developed on
Linux. The program occasionally dies, because the random number is used in
calculating an array index. It seems that the Linux version of rand()
returns a number less than RAND_MAX.

I am curious to know if this is a bug in the Windows or Linux version of
srand(), or they just like to be different. Or is the bug in the code from
the book?

The C# docs for Random.Next() are a little more clear:
A 32-bit signed integer greater than or equal to zero and less than
MaxValue.

Bill
 
Can't speak for gcc, but I know MSVC can return 0. I'm pretty sure most
compilers will generate a 0... MSDN for RAND_MAX says it is "the maximum
value that can be returned by the RAND function", so I assume it is
certainly meant to return RAND_MAX. Can't speak for gcc and the likes,
though... haven't used *nix in a few years ;)

hth,
-Dale
 
Marco said:
To get a random value between 0(inclusive) and x(exclusive),
you can use something like this:
#define RAND(x) ((size_t)((double)(x)*rand()/(1.0+RAND_MAX)))

That's OK if the number quality isn't essential, but it suffers from
non-uniformity. Doing it uniformly requires a loop that throws out
values in the partial range up to RAND_MAX.
 
Looks like the problem is with the code in the book (AI Application
Programming).

In the 4th edition of Harbison & Steele it says: "Successive calls to rand
return integer values in the range 0 to the largest representable positive
value of type int (inclusive) ...".

The libraries that the author was using probably have RAND_MAX set to the
maximum for a 32-bit int, so the problem is much more rare then in VS which
has RAND_MAX set to the maximum for a 16-bit int. It looks like when
Microsoft made the transition from 16 to 32 bit, they never changed the
value of RAND_MAX. The Microsoft documentation for rand leaves out the word
(inclusive).

And none of this is a problem, since I now know what to fix in the rest of
the examples from the book. I am only using C because that is what is in
the book. After I run the C code from the book to see how it works, I
translate it to C#.

Bill
 
Craig said:
That's OK if the number quality isn't essential, but it suffers from
non-uniformity. Doing it uniformly requires a loop that throws out
values in the partial range up to RAND_MAX.

I believe Marco's example is correct. The problem is with the simpler
(and more common)
x = (int) rand() % n;
 
Back
Top