Bug: random() can return 1.0

From: Andrew - Supernews <andrew+nonews(at)supernews(dot)com>
To: pgsql-hackers(at)postgresql(dot)org
Subject: Bug: random() can return 1.0
Date: 2006-01-19 22:40:41
Message-ID: slrndt05b9.1rvr.andrew+nonews@atlantis.supernews.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers pgsql-patches

src/backend/utils/adt/float.c:

/*
* drandom - returns a random number
*/
Datum
drandom(PG_FUNCTION_ARGS)
{
float8 result;

/* result 0.0-1.0 */
result = ((double) random()) / ((double) MAX_RANDOM_VALUE);

PG_RETURN_FLOAT8(result);
}

Whoever wrote this obviously did intend it to return values in [0.0,1.0]
but this makes it totally useless for generating uniform random ranges
in the usual way, since random() * N will return N with probability 2^-31.
The documentation is sufficiently imprecise about this to cause confusion
(seen in questions asked on the IRC channel), and the problem can't be
worked around at the application level without knowing the value of
MAX_RANDOM_VALUE in order to correct the range to [0.0,1.0).

--
Andrew, Supernews
http://www.supernews.com - individual and corporate NNTP services

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Simon Riggs 2006-01-19 22:47:13 Re: No heap lookups on index
Previous Message Tom Lane 2006-01-19 22:11:56 Re: un-vacuum?

Browse pgsql-patches by date

  From Date Subject
Next Message Bruce Momjian 2006-01-19 22:49:35 Re: Bug: random() can return 1.0
Previous Message Jim C. Nasby 2006-01-19 22:38:43 Re: Uninstall scripts for contrib