How to generate random numbers in SAS

You can generate a set of random numbers in SAS that are uniformly distributed by using the RAND function in the DATA step or by using the RANDGEN subroutine in SAS/IML software. (These same functions also generate random numbers from other common distributions such as binomial and normal.)

The syntax is simple. The following DATA step creates a data set that contains 10 random uniform numbers in the range (0,1):

Random uniform numbers in the interval (a,b)

If you want generate random decimal numbers in the interval (a,b), you have to scale and translate the values that are produced by RAND and RANDGEN. The width of the interval (a,b) is b-a, so the following statements produce random values in the interval (a,b):

a = -1; b = 1; /* example values */
x = a + (b-a)*u;

The same expression is valid in the DATA step and the SAS/IML language.

Random integers in SAS

You can use the FLOOR or CEIL functions to transform (continuous) random values into (discrete) random integers. In statistical programming, it is common to generate random integers in the range 1 to Max for some value of Max, because you can use those values as observation numbers (indices) to sample from data. The following statements generate random integers in the range 1 to 10:

Max = 10;
k = ceil( Max*u ); /* uniform integer in 1..Max */

If you want random integers between 0 and Max or between Min and Max, the FLOOR function is more convenient:

You can use the UNIVARIATE and FREQ procedures in Base SAS to see how closely the statistics of the sample match the characteristics of the populations. The PROC UNIVARIATE output is not shown, but the histograms show that the sample data for the u and x variables are, indeed, uniformly distributed on (0,1) and (-1,1), respectively. The PROC FREQ output shows that the k, n, and m variables contain integers that are uniformly distributed within their respective ranges. Only the output for the m variable is shown.

About Author

Rick Wicklin, PhD, is a distinguished researcher in computational statistics at SAS and is a principal developer of PROC IML and SAS/IML Studio. His areas of expertise include computational statistics, simulation, statistical graphics, and modern methods in statistical data analysis. Rick is author of the books Statistical Programming with SAS/IML Software and Simulating Data with SAS.

Yes, they are different. RANUNI, RANNOR, etc., are functions that use an older random number generator. Their statistical properties are not as good as the newer RAND function. ("Newer" means it's only been in SAS since the mid-1990s!) For small data sets and simple demo examples, it doesn’t matter which function you use. However, if you are doing serious Monte Carlo simulations and generating millions of random numbers, then the better statistical properties of the RAND function become important.

I am using VNORMAL for Monte Carlo simulations at the moment. Do you know which random number generator this function is using? I can't find anything in the SAS manual. Would it be better to use RANDNORMAL? I know RANDNORMAL allows you to use RANDSEED and VNORMAL doesn't but I didn't deem this very important.

Thank you for the interesting and very helpful writings on SAS random numbers.

I ran 36 instances of a SAS program in parallel on a cluster. I provided unique seed to each running instance. Every instance generated 4,000,000 (four million) random numbers using RANUNI. Total of 144,000,000 (=36 * 4 mln.) random numbers for all instances were needed. After all instances have completed, I noticed that about 2.8% of the random numbers (generated in all instances) were duplicated, even though unique seeds were used by the instances.

When I used STREAMINIT and then RAND("UNIFORM") to generate the random numbers, about 4% of the random numbers (generated in all instances) were duplicated.

In general, you shouldn't confuse INDEPENDENCE with UNIQUENESS. Random number generators try to achieve independence. There is nothing intrinsically wrong with getting a repeated value, just like there is nothing wrong with rolling a die and getting the same value multiple times. It happens often, and it doesn't mean that the die is unfair.

I caution against using RANUNI for large samples. RANUNI only provides 2 billion possible values. If you generate 144m obs in RANUNI, you shouldn't be surprised to get a repeated value. This is the famous Birthday Matching Problem, which I blogged about in the form of matching initials at a meeting.

I am curious: how are you determining that values are duplicated. PROC FREQ? PROC SORT with the NODUP option?

Thank you for the reply. I read your post - it is interesting and helpful. Thanks.

Please note, that when I use only one seed and generate 144m random numbers, I do not see any duplications.

Here is how I determine if that values are duplicated or not:
1. Assuming that every generated random number is placed (printed out) on a separate line of a file, for instance rand_nums.lst.
2. cat (Linux) command counts the number of all lines in the file. For instance:
cat rand_nums.lst | wc -l
3. sort (Linux) command counts the number of unique lines, For instance:
sort -nu rand_nums.lst | wc -l
4. If these number are the same then this means that the generated random numbers are unique.

I am a Danish master student. I am currently struggling with a simulation for my master thesis. The purpose of the simulation is to verify wether industrial merger waves exist in Europe or not.

I need to randomly generate x uniformly distributed numbers ('pseudo'-M&A's) between 1 and 120 (JanYear1, FebYear1...DecYear10) for every identified M&A-active industry (48 industries). And I need to repeat this step 1000 times. x is the observed number of M&A's in the industry under investigation.
- based on this blog post, I now think I know how to conduct the simulation in SAS.

My hurdle is that after the simulation process, I need to identify the volume of the highest 24-month concentration for each of the 1000 draws. Can you help me here, Rick? I need the 24-month concentrations to conclude whether an industrial merger wave exists or not for a given industry --> if in 99% of the draws the highest 24-month concentration is lower than the actually or observed peak concentration, there is significant evidence for the existence of an 2 year merger wave within the given industry, in that decade.

Random numbers are not necessarily unique. Consider rolling a six-sided die two times. About 1/6 of the time the random number 1-6 will be repeated! To get uniqueness you want to "sample without replacement" from the list of numbers that you want. You can use the METHOD=SRS method in PROC SURVEYSELECT to select samples without replacement. In PROC IML, you can use the SAMPLE function.

Hi Rick! Is it possible to use the RAND() function inside PROC IML? I tried doing that and it seems to work; I'm just concerned if it produces the same result as the RANDGEN subroutine. I've been reading some comments that inside PROC IML, the RANDGEN subroutine should be used. However, I don't need to generate one stream of random numbers every iteration. I need to generate just one random number, and the parameter of the distribution (say the binomial sample size) varies from iteration to iteration, so you can see my dilemma about using RANDGEN.

I do not see your dilemma about using RANDGEN. You can geneate 1 sample as efficiently with RANDGEN as with RAND. However, to answer your question: yes, you can call RAND from PROC IML. Furthermore, you can pass a vector of parameters to RAND and get out a vector of binomial sample sizes.

From what distribution? Uniform? Discrete uniform? Normal? I've written more than 30 articles on simultion, so you can find lots of examples by clicking on the "Simulation and Sampling" link in the right-hand sidebar. In particular, look at the DATA step in the second set of code in this article: http://blogs.sas.com/content/iml/2012/07/18/simulation-in-sas-the-slow-way-or-the-by-way/ It shows a DATA step with two nested loops. Make the outer loop go to 5 and the inner loop go to 7.

I was wondering if it's possible to do a similar exercise, but pulling a VECTOR of 2 bivariate normal variables? If I know the means and the variance-covariance matrix of my variables, can SAS randomly draw from the joint distribution?

Sorry to revive an old thread, but I was wondering what your thoughts were (and why it wasn't mentioned) on using ROUND() around the a+(b-a)*u formula for random integers in [a,b]? I originally used FLOOR()/CEIL() in my code, but lately (especially when I have a small interval, such as [1,5]) I have switched to ROUND() since FLOOR()/CEIL() bias away from b/a, respectively. I know that traditional discrete uniform distribution says that random draws of each value in an interval of K values should tend towards a 1/K distribution, but I don't believe the FLOOR()/CEIL() functions provide this.

Maybe I am misunderstanding what you are proposing. I didn't put ROUND around the a+(b-a)*u formula because the resulting integers are not uniformly distributed. For example, if I want uniform integers in the range {1,2,3,4,5}, it is incorrect to write the following:

Looks good, although I'd use lgnrm = exp(nr) in the DATA step and set THETA=0 in the HISTOGRAM stmt.
If you have more questions, please post to the SAS Support Communities. There are about 20 subcommunities there, such as SAS Statistical Procedures.

The advantage of the iCDF method is that is always works. However, it tends to be slower than direct transformation methods, such as used here.

Hi
I have a dataset for a one district in this district 16 Mandal and each Mandal have three type (Govt., Private, NGO,) 3500 school, I want a sample for each Mandal 1 got 1 private 1 NGO School total Number of sample are 48, whenever we run the programme the sample should be different, not same , could you help me how can I take a sample using SAS

These are 101 unique random numbers. Each number consists of 13 digits, out of which first 11 digits are sequential numbers and the 12th and 13th digits together form a random number.
These last two digits transform the 11 digit sequential number into a 13 digit random number. Thus when a sequential number is transformed into a random number by addition of 1 or 2 digits, such randomization does not need math based algorithm.
Even if the two digits are created by math based algorithms, there can be innumerable such algorithms that can create two digit random numbers.

Hence, my claim is that when 1, 2 or 3 randomly created digits are attached to the sequential number, you award randomness to it and such randomized sequential numbers are unpredictable.
Thus a SHORTEST POSSIBLE sequence of 11 digits can accommodate one billion unpredictable random numbers and a sequence of only 14 digits can accommodate one trillion unpredictable random numbers.

The number 98.40 is not an integer. If you are generating random integers in [0,99], then a particular integer (say, 98) will occur ON AVERAGE about 1% of the time, but you cannot predict when it will occur or how often it will appear in a particular sample. If you have more questions, please ask at the SAS Support Communities.

I remember i asked a question about generating random number with normal distribution and also require them within two numbers. E.g., numbers with 2 to 200 with a normal distribution of mean 90 std 10. Could you send me the link to this question again?