Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.misc -> Re: Random Functions with PL/SQL

Re: Random Functions with PL/SQL

From: Thomas Kyte <tkyte_at_us.oracle.com>
Date: 1998/01/28
Message-ID: <34d39733.7339894@192.86.155.100>#1/1

On Tue, 27 Jan 1998 15:48:08 -0800, "Brad Orahood" <brad_at_fta.com> wrote:

>Does anyone out there have a good reliable random
>number generator that they use in PL/SQL?
>
>Thanks,
>Brad Orahood
>
>

This one works just like the C rand() function. If you do a

$ man rand

it'll tell you the properties of the random number generator...

create or replace package random
is

        pragma restrict_references( random, WNDS, RNPS );

        procedure srand( new_seed in number );

	function rand return number;
	pragma restrict_references( rand, WNDS  );

	procedure get_rand( r OUT number );

	function rand_max( n IN number ) return number;
	pragma restrict_references( rand_max, WNDS);

	procedure get_rand_max( r OUT number, n IN number );

end random;
/

create or replace package body random
is

	multiplier	constant number         := 22695477;
	increment	constant number        	:= 1;
	"2^32"		constant number			:= 2 ** 32;
	"2^16"		constant number         := 2 ** 16;
	"0x7fff"	constant number         := 32767;
	Seed		number := 1;
--
	procedure srand( new_seed in number ) 
	is
	begin
		Seed := new_seed;
	end srand;
--
	function rand return number
	is
	begin
		seed := mod( multiplier * seed + increment, "2^32" );
		return bitand( seed/"2^16", "0x7fff" );
	end rand;
--
	procedure get_rand( r OUT number ) 
	is
	begin
		r := rand;
	end get_rand;
--
	function rand_max( n IN number ) return number 
	is
	begin
		return mod( rand, n ) + 1;
	end rand_max;
--
	procedure get_rand_max( r OUT number, n IN number ) 
	is
	begin
		r := rand_max( n );
	end get_rand_max;
--
begin
	select userenv( 'SESSIONID' ) into seed from dual;
end random;
/

 
Thomas Kyte
tkyte_at_us.oracle.com
Oracle Government
Bethesda MD
 
http://govt.us.oracle.com/    -- downloadable utilities
 
----------------------------------------------------------------------------
Opinions are mine and do not necessarily reflect those of Oracle Corporation
 
Anti-Anti Spam Msg: if you want an answer emailed to you, 
you have to make it easy to get email to you.  Any bounced
email will be treated the same way i treat SPAM-- I delete it.
Received on Wed Jan 28 1998 - 00:00:00 CST

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US