From: | Szymon Guz <mabewlun(at)gmail(dot)com> |
---|---|
To: | Ian Lawrence Barwick <barwick(at)gmail(dot)com> |
Cc: | bricklen <bricklen(at)gmail(dot)com>, Karel Riveron Escobar <kescobar(at)estudiantes(dot)uci(dot)cu>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: Random numbers |
Date: | 2013-05-25 16:10:52 |
Message-ID: | CAFjNrYtH7tZmirGX3tPANAW68tYhgzUzsm00wBZC3mDvtjB1yg@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 25 May 2013 17:56, Ian Lawrence Barwick <barwick(at)gmail(dot)com> wrote:
> 2013/5/26 bricklen <bricklen(at)gmail(dot)com>:
> >
> > On Sat, May 25, 2013 at 8:45 AM, Karel Riveron Escobar
> > <kescobar(at)estudiantes(dot)uci(dot)cu> wrote:
> >>
> >> I want to generate random numbers in Pl/pgSQL. How can I do this?
> >> To be more specific, I have to generate random numbers among 0 and 5.
> >
> >
> > One way:
> > select n from unnest(ARRAY[0,1,2,3,4,5]) n order by random() limit 1;
>
> somewhat shorter:
> SELECT (random() * 5)::INT
>
>
I'd rather use something like:
SELECT floor(random()*6)::INT
as this gives uniform results distribution.
Compare the two below queries, in the first you have twice less results for
0 and 5 than for the rest numbers.
WITH x AS (SELECT (random()*5)::INT r FROM generate_series(1,1000*1000))
SELECT r, count(*) FROM x GROUP BY r ORDER BY r ;
WITH x AS (SELECT floor(random()*6)::INT r FROM
generate_series(1,1000*1000)) SELECT r, count(*) FROM x GROUP BY r ORDER BY
r ;
regards
Szymon
From | Date | Subject | |
---|---|---|---|
Next Message | Karel Riveron Escobar | 2013-05-25 16:14:33 | Re: Random numbers |
Previous Message | Karel Riveron Escobar | 2013-05-25 16:04:48 | Re: Random numbers |