Generate Random Number Between 1 and 10 in SAS

It is a common task to generate random numbers in SAS. Here, I will demonstrate different approaches to generate random integers. For simplicity, I will demonstrate how to generate a random integer between 1 and 10. The examples are easily extendable to more sophisticated situations.

A Random Integer Between 1 and 10

First, let us generate a random number between 1 and 10. We do so in the simplest possible way. From SAS 9.4M5, the Rand Function supports the ‘Integer’ argument. We simply use the ‘Integer’ argument and specify the min and max ranges like this.

data _null_;
   r = rand("integer", 1, 10);
   /* r = rand("integer", 10); equivalent */
   put r;
run;

Before SAS 9.4M5, we have to do something else. Therefore, the standard approach is to generate a uniform random number between 0 and 1. Then, multiply by the upper limit (10) and use the Ceil Function to get the appropriate integer.

data _null_;
   r = ceil(rand('uniform')*10);
   put r=;
run;

A Random Integer Between 5 and 10

Next, suppose that the lower limit of the desired range is not 1. Instead it is some other integer. Let us generate a random number between 5 and 10. We can use the approach below. Obviously, this task is easy with the ‘Integer’ argument to the Rand Function. However, if we do not have the proper SAS version, we have to do something like this instead.

data _null_;
   min = 5;
   max = 10;
   r = min + floor(rand("uniform") * (1 + max - min));
   put r;
run;

Integer Range Limitation of Rand Function

Finally, let us take a look at generating large integers in SAS. While the simplicity of the Integer argument to the Rand Function is intriguing, it has its shortcomings. It turns out that the Rand Function with the Integer argument can only generate integers in the range [-2**32+1 : 2**32-1]. [-2.147.483.647 : +2.147.483.647] which means a little over/under 2 billion. The old-fashioned approach using the Uniform Argument can handle a wider range of [-2**53 : +2**53] under ASCII encoding. [-2**56 : +2**56] under EBCDIC encoding. Run the code below and verify.

data _null_;
   r = rand('integer', 2147483647, 2147483647); /* Works */
   r = rand('integer', 2147483648, 2147483648); /* Error */
run;

Summary

In this example page, we provide usable code to generate random numbers between some min and max value in SAS. This is a common, but fairly simple task. Especially since the Rand Function supports the Integer Argument in newer SAS versions. However, if we want to generate integers in a very wide range, the old-fashioned approach may be the way to go. Because it handles a wider range than the newer approach.

For more information, read the two posts on the Do Loop Blog How to generate random numbers in SAS and How to generate random integers in SAS.

You can download the entire code from this page here.