random.sql
create or replace package random is function f_random(r in number) return number; function f_random2 return number; end; / create or replace package body random is --/* Linear congruential random number generator */ -- m constant number:=100000000; m1 constant number:=10000; b constant number:=31415821; -- a number; -- the_date date; days number; secs number; -- --/*-------------------------- mult ---------------------------*/ --/* Private utility function */ -- function mult(p in number, q in number) return number is p1 number; p0 number; q1 number; q0 number; begin p1:=trunc(p/m1); p0:=mod(p,m1); q1:=trunc(q/m1); q0:=mod(q,m1); return(mod((mod(p0*q1+p1*q0,m1)*m1+p0*q0),m)); end mult; /* mult */ -- --/*-------------------------- f_random --------------------------*/ --/* Returns random integer between [0, r-1] */ -- function f_random (r in number) return number is begin -- /* generate a random number and set it to be the new seed */ a:=mod(mult(a,b)+1,m); -- -- /* convert it to integer between [0, r-1] and return it */ return(trunc((trunc(a/m1)*r)/m1)); end f_random; -- /* f_random */ -- --/*-------------------------- f_random2 --------------------------*/ --/* Returns random real between [0, 1] */ -- function f_random2 return number is begin -- /* generate a random number and set it to be the new seed */ a:=mod(mult(a,b)+1,m); -- /* return it */ return(a/m); end f_random2; -- /* f_random2 */ -- -- begin --/* package body random */ -- /* Generate an initial seed "a" based on system date */ -- /* (Must be connected to database.) */ the_date:=sysdate; days:=to_number(to_char(the_date, 'J')); secs:=to_number(to_char(the_date, 'SSSSS')); a:=days*24*3600+secs; end; -- /* package body random */ / /************** Example ***************/ declare ln NUMBER; begin ln:= random.f_random(10.5); dbms_output.put_line(to_char(ln)); end; / declare ln NUMBER; begin dbms_output.enable(1000000); ln:= smithj.random.f_random2; dbms_output.put_line(to_char(ln)); end; /