Home » How to Use the Equivalent of runif() in Python

How to Use the Equivalent of runif() in Python

by Erma Khan

In the R programming language, we can use the runif() function to generate a vector of random values that follow a uniform distribution with a specific minimum and maximum value.

For example, the following code shows how to use runif() to create a vector of 8 random values that follow a uniform distribution with a minimum value of 5 and maximum value of 10:

#make this example reproducible
set.seed(1)

#generate vector of 8 values that follow uniform distribution with min=5 and max=10
runif(n=8, min=5, max=10)

[1] 6.327543 6.860619 7.864267 9.541039 6.008410 9.491948 9.723376 8.303989

The equivalent of the runif() function in Python is the np.random.uniform() function, which uses the following basic syntax:

np.random.uniform(low=0, high=1, size=None)

where:

  • low: Minimum value of the distribution
  • high: Maximum value of the distribution
  • size: Sample size

The following example shows how to use this function in practice.

Example: Using the Equivalent of runif() in Python

The following code shows how to use the np.random.uniform() function to generate an array of random values that follow a uniform distribution with a specific minimum and maximum value:

import numpy as np

#make this example reproducible
np.random.seed(1)

#generate array of 8 values that follow uniform distribution with min=5 and max=10
np.random.uniform(low=5, high=10, size=8)

array([7.08511002, 8.60162247, 5.00057187, 6.51166286, 5.73377945,
       5.46169297, 5.93130106, 6.72780364])

The result is a NumPy array that contains 8 values generated from a uniform distribution with a minimum value of 5 and maximum value of 10.

You can also create a histogram using Matplotlib to visualize a normal distribution generated by the np.random.uniform() function:

import numpy as np
import matplotlib.pyplot as plt

#make this example reproducible
np.random.seed(1)

#generate array of 200 values that follow uniform distribution with min=5 and max=10
data = np.random.uniform(low=5, high=10, size=200)

#create histogram to visualize distribution of values
plt.hist(data, bins=30, edgecolor='black')

The x-axis shows the values from the distribution and the y-axis shows the frequency of each value.

Notice that the x-axis ranges from 5 to 10 since these were the minimum and maximum values that we specified for the distribution.

Note: You can find the complete documentation for the np.random.uniform() function here.

Additional Resources

The following tutorials explain how to perform other common operations in pandas:

How to Create Pandas DataFrame with Random Data
How to Randomly Sample Rows in Pandas
How to Shuffle Rows in a Pandas DataFrame

Related Posts