Random integer in a range

From PostgreSQL wiki

(Difference between revisions)
Jump to: navigation, search
Line 13: Line 13:
 
$imin = $_[1];
 
$imin = $_[1];
 
$imax = $_[0]; }
 
$imax = $_[0]; }
$_number_ = ( (rand) * ($imax + 1));
+
$_number_ = $imin + ( (rand) * ($imax -$imin + 1));
while (($_number_ < $imin) || ( $_number_ > $imax)){
+
        return sprintf "%d",$_number_;
        $_number_ = ( (rand) * ($imax + 1));}
+
return sprintf "%d",$_number_;
+
 
+
 
$pg_round_random_range$;
 
$pg_round_random_range$;
 
</source>
 
</source>
  
  
 
+
If you don't want to control the arguments:
Would it not be better to preserve the random distribution within the desired range:
+
<source lang="perl">
+
$_number_ = $imin + ( (rand) * ($imax -$imin + 1));
+
return sprintf "%d",$_number_;
+
</source>
+
 
+
 
<source lang='perl'>
 
<source lang='perl'>
 
CREATE OR REPLACE FUNCTION pg_round_random_range(int, int) RETURNS integer  
 
CREATE OR REPLACE FUNCTION pg_round_random_range(int, int) RETURNS integer  

Revision as of 06:25, 19 March 2010

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_ = $imin + ( (rand) * ($imax -$imin + 1));
        return sprintf "%d",$_number_;
$pg_round_random_range$;


If you don't want to control the arguments:

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