Random integer in a range

From PostgreSQL wiki

Revision as of 20:43, 2 February 2010 by 3manuek (Talk | contribs)

Jump to: navigation, search

Snippets

Random integer in a range

Works with PostgreSQL

Any version

Written in

PL/Perl

Depends on

Nothing


by Emanuel '3m4nuek' CF

CREATE OR REPLACE FUNCTION pg_round_random_range(int, int) RETURNS integer 
LANGUAGE plperl IMMUTABLE RETURNS NULL ON NULL INPUT
AS $pg_round_random_range$
	my($imin, $imax) = @_;	
	if ($_[0] == $_[1]){
		return $_[0];	}
	if($imin > $imax){
		$imin = $_[1];
		$imax = $_[0];	}	
	$_number_ = ( (rand) * ($imax + 1));
	while (($_number_ < $imin) || ( $_number_ > $imax)){
    	    $_number_ = ( (rand) * ($imax + 1));}
	return sprintf "%d",$_number_;	
 
$pg_round_random_range$;


Would it not be better to preserve the random distribution within the desired range:

$_number_ = $imin + ( (rand) * ($imax -$imin + 1));
return sprintf "%d",$_number_;
CREATE OR REPLACE FUNCTION pg_round_random_range(int, int) RETURNS integer 
LANGUAGE plperl IMMUTABLE RETURNS NULL ON NULL INPUT
AS $pg_round_random_range$
   my($imin, $imax) = @_;	
   $_number_ = $imin + ( (rand) * ($imax -$imin + 1));
   return sprintf "%d",$_number_;
$pg_round_random_range$;
Personal tools