Re: [HACKERS] random() function produces wrong range

Tom Lane <tgl@sss.pgh.pa.us>

From: Tom Lane <tgl@sss.pgh.pa.us>
To: Thomas Lockhart <lockhart@alumni.caltech.edu>
Cc: pgsql-hackers@postgresql.org, pgsql-general@postgresql.org
Date: 2000-08-02T14:07:48Z
Lists: pgsql-hackers
Thomas Lockhart <lockhart@alumni.caltech.edu> writes:
> The Linux man pages indicate that the behavior and underlying
> implementation of random() and rand() are the same (so I just picked
> one).

Ah, well, there's your problem.  Whoever did this part of the library
on Linux took shortcuts.  On older-line systems, rand() is a
considerably older and crummier generator than random().  It would
definitely not be a wise decision to use rand() instead.

It appears that on SysV-heritage machines, rand() delivers 15-bit
results (which is what I'm getting) whereas on BSD-heritage platforms
it produces 31-bit results.  But even the BSD machines say

     The spectral properties of rand() leave a great deal  to  be
     desired.   drand48(3)  and  random(3)  provide  much better,
     though more elaborate, random-number generators.

(quote from SunOS 4.1 man page for rand()).

I believe using random() is the right thing.  The portability bug here
is the assumption that RAND_MAX applies to random() (or is even defined;
none of the man pages I've looked at so far mention it).  But all the
machines say that the output of random() is 31 bits, so INT_MAX should
work.

			regards, tom lane