How to Use the Equivalent of rnorm() in Python


In the R programming language, we can use the rnorm() function to generate a vector of random values that follow a normal distribution with a specific mean and standard deviation.

For example, the following code shows how to use rnorm() to create a vector of 8 random values that follow a normal distribution with a mean of 5 and standard deviation of 2:

#make this example reproducible
set.seed(1)

#generate vector of 8 values that follow normal distribution with mean=5 and sd=2
rnorm(n=8, mean=5, sd=2)

[1] 3.747092 5.367287 3.328743 8.190562 5.659016 3.359063 5.974858 6.476649

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

np.random.normal(loc=0, scale=1, size=None)

where:

  • loc: Mean of the distribution
  • scale: Standard deviation of the distribution
  • size: Sample size

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

Example: Using the Equivalent of rnorm() in Python

The following code shows how to use the np.random.normal() function to generate an array of random values that follow a normal distribution with a specific mean and standard deviation.

import numpy as np

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

#generate array of 8 values that follow normal distribution with mean=5 and sd=2
np.random.normal(loc=5, scale=2, size=8)

array([8.24869073, 3.77648717, 3.9436565 , 2.85406276, 6.73081526,
       0.39692261, 8.48962353, 3.4775862 ])

The result is a NumPy array that contains 8 values generated from a normal distribution with a mean of 5 and a standard deviation of 2.

You can also create a histogram using Matplotlib to visualize a normal distribution generated by the np.random.normal() 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 normal distribution with mean=5 and sd=2
data = np.random.normal(loc=5, scale=2, size=200)

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

We can see that the distribution of values is roughly bell-shaped with a mean located at 5 and a standard deviation of 2.

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

Additional Resources

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

How to Calculate & Plot the Normal CDF in Python
How to Plot a Normal Distribution in Python
How to Test for Normality in Python

Leave a Reply

Your email address will not be published.