Time for action – drawing the lognormal distribution

Let's visualize the lognormal distribution and its probability density function with a histogram. Perform the following steps:

  1. Generate random numbers using the normal function from the random NumPy module.
    N=10000
    lognormal_values = np.random.lognormal(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(lognormal_values, np.sqrt(N), normed=True, lw=1)
    sigma = 1
    mu = 0
    x = np.linspace(min(bins), max(bins), len(bins))
    pdf = np.exp(-(numpy.log(x) - mu)**2 / (2 * sigma**2))/ (x * sigma * np.sqrt(2 * np.pi))
    plt.plot(x, pdf,lw=3)
    plt.show()

    The fit of the histogram and theoretical pdf is excellent, as you can see in the following screenshot:

    Time for action – drawing the lognormal distribution

What just happened?

We visualized the lognormal distribution using the lognormal function from the random NumPy module. We did this by drawing the curve of the theoretical probability density function and a histogram of randomly generated values (see lognormaldist.py).

import numpy as np
import matplotlib.pyplot as plt

N=10000
lognormal_values = np.random.lognormal(size=N)
dummy, bins, dummy = plt.hist(lognormal_values, np.sqrt(N), normed=True, lw=1)
sigma = 1
mu = 0
x = np.linspace(min(bins), max(bins), len(bins))
pdf = np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))/ (x * sigma * np.sqrt(2 * np.pi))
plt.plot(x, pdf,lw=3)
plt.show()
..................Content has been hidden....................

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