Skip site navigation (1) Skip section navigation (2)

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

From: Peter Eisentraut <peter_e(at)gmx(dot)net>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: PostgreSQL Development <pgsql-hackers(at)postgreSQL(dot)org>
Subject: Re: Re: [GENERAL] random() function produces wrong range
Date: 2000-08-04 22:03:19
Message-ID: Pine.LNX.4.21.0008050002340.1568-100000@localhost.localdomain (view raw or flat)
Thread:
Lists: pgsql-hackers
Tom Lane writes:

> Oh, that's interesting.  What platform do you use?  If RAND_MAX applies
> to random() on some machines that'd probably explain why the code is
> written like it is.  But on my box (HPUX) the rand() function is old
> and crufty and considerably different from random().

rand() and RAND_MAX are defined by ANSI C, random() is a BSD-ism. I
suggest you use the former. Also, while you're at it, this is a snippet
from the C FAQ:

13.16:  How can I get random integers in a certain range?
 
A:      The obvious way,
 
                rand() % N              /* POOR */
 
        (which tries to return numbers from 0 to N-1) is poor, because
        the low-order bits of many random number generators are
        distressingly *non*-random.  (See question 13.18.)  A better
        method is something like
 
                (int)((double)rand() / ((double)RAND_MAX + 1) * N)
 
        If you're worried about using floating point, you could use
 
                rand() / (RAND_MAX / N + 1)
 
        Both methods obviously require knowing RAND_MAX (which ANSI
        #defines in <stdlib.h>), and assume that N is much less than
        RAND_MAX.
 
        (Note, by the way, that RAND_MAX is a *constant* telling you
        what the fixed range of the C library rand() function is.  You
        cannot set RAND_MAX to some other value, and there is no way of
        requesting that rand() return numbers in some other range.)
 
        If you're starting with a random number generator which returns
        floating-point values between 0 and 1, all you have to do to get
        integers from 0 to N-1 is multiply the output of that generator
        by N.
 
        References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172.


-- 
Peter Eisentraut                  Sernanders väg 10:115
peter_e(at)gmx(dot)net                   75262 Uppsala
http://yi.org/peter-e/            Sweden


Responses

pgsql-hackers by date

Next:From: The Hermit HackerDate: 2000-08-04 22:31:00
Subject: Re: Installation layout idea
Previous:From: Peter EisentrautDate: 2000-08-04 22:01:42
Subject: Re: New Privilege model purposal

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group