random
module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
random.normalvariate()
normalvariate()
is an inbuilt method of the random
module. It is used to return a random floating point number with normal distribution.
Syntax : random.normalvariate(mu, sigma)
Parameters :
mu : mean
sigma : standard deviationReturns : a random normal distribution floating number
Example 1:
# import the random module import random # determining the values of the parameters mu = 100 sigma = 50 # using the normalvariate() method print (random.normalvariate(mu, sigma)) |
Output :
110.86699628241412
Example 2: We can generate the number multiple times and plot a graph to observe the normal distribution.
# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a # list nums = [] mu = 100 sigma = 50 for i in range ( 100 ): temp = random.normalvariate(mu, sigma) nums.append(temp) # plotting a graph plt.plot(nums) plt.show() |
Output :
Example 3: We can create a histogram to observe the density of the normal distribution.
# import the required libraries import random import matplotlib.pyplot as plt # store the random numbers in a list nums = [] mu = 100 sigma = 50 for i in range ( 10000 ): temp = random.normalvariate(mu, sigma) nums.append(temp) # plotting a graph plt.hist(nums, bins = 200 ) plt.show() |
Output :