This tutorial shows how to generate a sample of normal distrubution using NumPy in Python. The following shows syntax of two methods.
Method 1: It can change the default values (Default: mu=0 and sd=1).
np.random.normal(mu=0, sigma=1, size)
Method 2: It can only generate numbers of standard normal (mu=0 and sd=1). But, it can have different shapes by changing (d0, d1, …, dn).
np.random.randn(d0, d1, …, dn)
Example for Method 1
The following uses np.random.normal() to generate a sample of normal distribution using Numpy. The Python code sets mean mu = 5
and standard variance sigma = 1
.
# import numpy
import numpy as np
# set mean and standard deviation
mu, sigma = 5, 1
# set seed
np.random.seed(123)
# generate a set of 10 numbers using Numpy function
y = np.random.normal(mu, sigma, 10)
# print out these 10 numbers
print("Normal Distribution (mu=5, sigma=1) array: \n", y)
The following is the print out of these 10 numbers that following normal distribution N(mu=5, sigma=1).
Normal Distribution (mu=5, sigma=1) array: [3.9143694 5.99734545 5.2829785 3.49370529 4.42139975 6.65143654 2.57332076 4.57108737 6.26593626 4.1332596 ]
Example for Method 2
The following uses np.random.randn (d0, d1, …, dn) to generate a sample of standard normal distribution using Numpy. The Python code sets d0= 5
and d1 = 3
. Thus, it will generate an array of 5×3.
# import numpy
import numpy as np
# set seed
np.random.seed(123)
# Set size of 5x3 array
Array_2D_standard_normal_distribution = np.random.randn(5,3)
print("Standard Normal Distribution array (5x3): \n", Array_2D_standard_normal_distribution)
The following is the output, which shows an array of 5×3. All the numbers in this array follows the standard normal distribution (i.e., mu=0, and sigma =1).
Standard Normal Distribution array (5x3): [[-1.0856306 0.99734545 0.2829785 ] [-1.50629471 -0.57860025 1.65143654] [-2.42667924 -0.42891263 1.26593626] [-0.8667404 -0.67888615 -0.09470897] [ 1.49138963 -0.638902 -0.44398196]]
Further Reading
The following is a tutorial about generating random numbers using Numpy in Python.