Showing posts with label random numbers in Oracle. Show all posts
Showing posts with label random numbers in Oracle. Show all posts

Sunday, October 21, 2012

Oracle Normal Distribution Function

Oracle function dbms_random.normal generates a standard normal distribution number with zero mean and one standard deviation.
SQL> select dbms_random.normal from dual;
NORMAL
----------
.781195382
The following query generates 6,000 random numbers using dbms_random.normal and then calculate their mean and standard deviation.We can see that their mean is close to zero and standard deviation close to one.
SQL> select avg(v), stddev(v), count(1) from (select dbms_random.normal v from V_6K_OBS);
AVG(V) STDDEV(V) COUNT(1)
---------- ---------- ----------
-.00110804 1.00954138 6000

Wednesday, October 03, 2012

More on random sampling in Oracle

The earlier post Random Sampling using SQL uses dbms_random.random to generate random numbers. A better function is dbms_random.value which generates uniformly distributed random number greater than or equal to 0 and less than 1.
We can rewrite random sampling scripts as the following.
Step 1 . Create random numbers.
create table tbl_app_id_w_rnd as select app_id, dbms_random.value rnd from CELL_PHONE_SERVICE_APPS;
Step 2. Create a view that contains 30% of the records.
create view v_data_testing as select a.* from CELL_PHONE_SERVICE_APPS a, tbl_app_id_w_rnd b where a.app_id=b.app_id and rnd <=0.3;

Tuesday, August 28, 2012

Random number generators


There are many random generators that can be used for random sampling  such as rand() in SAS, dbms_random.rand() in Oracle, rand() in Excel spreadsheet. I have helped implement a Winchmann- Hill random generator using PL/SQL. Here is a link to WH algorithm (http://www2.imperial.ac.uk/~hohs/S9/2007-2008/wichmannhill.pdf).

The reason to implement Winchmann-Hill random generator using PL/SQL was that we wanted to replicate the sequence of random numbers precisely given the same random seed. We did not want to use SAS or Oracle random functions because we do not know how the details of their algorithms. We want to build WH random generators that work consistently across platforms, i.e., SAS and Oracle database. This is easier said than done. One of the lessons we learnt was that SAS integer can only have 17 digits while Oracle integer support 38 digits. We have to make sure that the random seed is not too large.