Random integer in a range

From PostgreSQL wiki

(Difference between revisions)
Jump to: navigation, search
(proposed an alternative, fixed logical error in while statement since (a<b && a>c) is always false with b < c.)
Line 27: Line 27:
 
$_number_ = $imin + ( (rand) * ($imax -$imin + 1));
 
$_number_ = $imin + ( (rand) * ($imax -$imin + 1));
 
return sprintf "%d",$_number_;
 
return sprintf "%d",$_number_;
 +
</source>
 +
 +
<source lang='perl'>
 +
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$;
 
</source>
 
</source>
  
  
 
[[Category:PL/Perl]]
 
[[Category:PL/Perl]]

Revision as of 20:43, 2 February 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_ = ( (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