Generating Random Numbers from Exponential distribution¶
Faisal Qureshi
faisal.qureshi@ontariotechu.ca
Copyright information¶
© Faisal Qureshi
License¶
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.In [1]:
import numpy as np
import matplotlib.pyplot as plt
Using numpy's method¶
In [9]:
n = 100000
x = np.empty(n)
for i in range(n):
x[i] = np.random.exponential()
plt.figure(figsize=(4,4))
plt.title(f'Exponential')
plt.hist(x, bins=np.linspace(0,10,100));
Using cdf inverse method¶
In [10]:
def inv_cdf_of_exponential(mu, u):
return - mu * np.log( u )
def gen_samples_from_exponential_using_inv_cdf(n):
mu = 1
x = np.empty(n)
for i in range(0,n):
u = np.random.rand()
x[i] = inv_cdf_of_exponential(mu, u)
return x
Sample histogram¶
In [11]:
x_cdf = gen_samples_from_exponential_using_inv_cdf(n)
plt.figure(figsize=(4,4))
plt.title(f'Exponential')
plt.hist(x, bins=np.linspace(0,10,100), color='blue', alpha=0.2, label='builtin');
plt.hist(x_cdf, bins=np.linspace(0,10,100), color='red', alpha=0.2, label='inv cdf');
plt.legend()
Out[11]:
<matplotlib.legend.Legend at 0x1189ff790>
In [ ]: