Re: random() function produces wrong range - Mailing list pgsql-hackers

From Malcolm Beattie
Subject Re: random() function produces wrong range
Date
Msg-id 20000802152145.D21735@sable.ox.ac.uk
Whole thread Raw
In response to Re: random() function produces wrong range  (Tom Lane <tgl@sss.pgh.pa.us>)
Responses Re: random() function produces wrong range  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-hackers
Tom Lane writes:
> 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.

Why? Linux is compliant with the Single Unix Standard v2 from my brief
reading of it. The only fragile part is the man page for random(3)
which on Linux says "range from 0 to RAND_MAX" whereas SuSv2 says
"range from 0 to 2^31-1". Since RAND_MAX on Linux is actually 2^31-1
anyway, it is still correct albeit misleading. Documentation bug, say.

> 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.

SuSv2 says explicitly 2^31-1 so you should use that, otherwise you'll
be non-portable to platforms with 64-bit ints, for example.

--Malcolm

-- 
Malcolm Beattie <mbeattie@sable.ox.ac.uk>
Unix Systems Programmer
Oxford University Computing Services


pgsql-hackers by date:

Previous
From: Tom Lane
Date:
Subject: Re: random() function produces wrong range
Next
From: Bruce Momjian
Date:
Subject: Re: mac.c