Re: random() function produces wrong range

From: Malcolm Beattie <mbeattie(at)sable(dot)ox(dot)ac(dot)uk>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Thomas Lockhart <lockhart(at)alumni(dot)caltech(dot)edu>, pgsql-hackers(at)postgresql(dot)org, pgsql-general(at)postgresql(dot)org
Subject: Re: random() function produces wrong range
Date: 2000-08-02 14:21:45
Message-ID: 20000802152145.D21735@sable.ox.ac.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

Tom Lane writes:
> Thomas Lockhart <lockhart(at)alumni(dot)caltech(dot)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(at)sable(dot)ox(dot)ac(dot)uk>
Unix Systems Programmer
Oxford University Computing Services

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message brianb-pggeneral 2000-08-02 14:27:13 Re: disable multiple queries
Previous Message Tom Lane 2000-08-02 14:07:48 Re: [HACKERS] random() function produces wrong range

Browse pgsql-hackers by date

  From Date Subject
Next Message Bruce Momjian 2000-08-02 14:28:03 Re: mac.c
Previous Message Tom Lane 2000-08-02 14:07:48 Re: [HACKERS] random() function produces wrong range