How to Generate Uniformly Distributed Random Numbers in R

To generate uniformly distributed random numbers in R, you can use the “runif()” function. The runif() is a built-in function that “generates random numbers from a uniform, continuous probability distribution with a flat shape”.

The uniform distribution in R is a continuous probability distribution with a flat shape, while the normal distribution is a continuous probability distribution with a bell-shaped curve.

Generate ten uniformly distributed random numbers from 0 to 1 in R

To generate ten uniformly distributed random numbers from 0 to 1 in R, use the runif() function and pass the three arguments. The first is 10, the second is the min value which is 0, and the third is the max value which is 1.

set.seed(123)

random_numbers <- runif(10, min = 0, max = 1)

print(random_numbers)

Output

[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673 0.0455565 0.5281055
[8] 0.8924190 0.5514350 0.4566147

In this example, we used the runif() function that takes the length of the generating numbers, 10, and then min and max values. The min and max values are the upper and lower ranges in which we need to generate random numbers between.

You can see from the output that it generates ten uniformly distributed random numbers from 0 to 1.

By default, the runif() function generates random numbers with a precision of 53 bits, which is the maximum precision supported by R.

To generate random numbers with different precision, use the runif() function and pass the bits argument.

Generating random numbers from a specified range in R

You can use the runif() function to generate random numbers from a uniform distribution over a provided range in R.

Let’s generate 20 uniformly distributed random numbers from 15 to 25 using the runif() function.

set.seed(123)

random_numbers <- runif(20, min = 15, max = 25)

print(random_numbers)

Output

[1] 17.87578 22.88305 19.08977 23.83017 24.40467 15.45556 20.28105 23.92419
[9] 20.51435 19.56615 24.56833 19.53334 21.77571 20.72633 16.02925 23.99825
[17] 17.46088 15.42060 18.27921 24.54504

In this example, we passed the 20 as the first argument, min = 15 and max = 25, because we want 20 random numbers between 15 to 25.

You can see from the output that it generates 20 random numbers between the 15 to 25 range.

Difference between runif() and rnorm() function

The main difference between runif() and rnorm() is that the runif() function generates random numbers from a uniform distribution, while the rnorm() function generates random numbers from a normal distribution.

Leave a Comment