Time for action – drawing a normal distribution

Random numbers can be generated from a normal distribution and their distribution may be visualized with a histogram. To draw a normal distribution, perform the following steps:

  1. Generate random numbers for a given sample size using the normal function from the random NumPy module.
    N=10000
    normal_values = np.random.normal(size=N)
  2. Draw the histogram and theoretical pdf: Draw the histogram and theoretical pdf with a center value of 0 and standard deviation of 1. We will use Matplotlib for this purpose.
    dummy, bins, dummy = plt.hist(normal_values, np.sqrt(N), normed=True, lw=1)
    sigma = 1
    mu = 0
    plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ),lw=2)
    plt.show()

    In the following screenshot, we see the familiar bell curve:

    Time for action – drawing a normal distribution

What just happened?

We visualized the normal distribution using the normal function from the random NumPy module. We did this by drawing the bell curve and a histogram of randomly generated values (see normaldist.py).

import numpy as np
import matplotlib.pyplot as plt

N=10000

normal_values = np.random.normal(size=N)
dummy, bins, dummy = plt.hist(normal_values, np.sqrt(N), normed=True, lw=1)
sigma = 1
mu = 0
plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (bins - mu)**2 / (2 * sigma**2) ),lw=2)
plt.show()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset