Talk:Random Range

From PostgreSQL wiki

Jump to: navigation, search

Over 4096 samples, this produces a clear bias when used with the int casting syntax. A method involving floor would be more suitable if going for an integer range.

artifice=# SELECT count(*) FROM rands WHERE v = 1;
217
artifice=# SELECT count(*) FROM rands WHERE v = 2;
469
artifice=# SELECT count(*) FROM rands WHERE v = 3;
480
artifice=# SELECT count(*) FROM rands WHERE v = 4;
455
artifice=# SELECT count(*) FROM rands WHERE v = 5;
467
artifice=# SELECT count(*) FROM rands WHERE v = 6;
430
artifice=# SELECT count(*) FROM rands WHERE v = 7;
468
artifice=# SELECT count(*) FROM rands WHERE v = 8;
408
artifice=# SELECT count(*) FROM rands WHERE v = 9;
478
artifice=# SELECT count(*) FROM rands WHERE v = 10;
224

Jimbostrudel 00:11, 24 February 2012 (UTC)

This is because 1 comes from the range 1 to 1.499.. which is just a range of just under 0.5, but 2 comes from 1.5 to 2.4999 which is just under 1, so twice as likely to be created. The same goes for 10 which is 9.5 to 10. If you want them to be equal, you'd have to have a range of 0.5 to 10.4999999, or instead of casting to an int, use floor(random(1,11)), neither of which are intuitive for the purposes sought here.

Thom 17:53, 25 February 2012 (GMT)

Personal tools