I need to generate a truncated gamma distribution pdf curve and histogram in Python 3.2 on win7.
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sps
shape, scale = 2., 2. # mean and dispersion
counter =0
s = []
upper_bound = 4
lower_bound = 0.5
while (counter <= 1000):
t = np.random.gamma(shape, scale, 1)
if (lower_bound <= t <= upper_bound) :
s.append(t)
counter += 1
count, bins, ignored = plt.hist(s, 50, normed=True)
// this part take s very long time
y = bins**(shape-1)*(np.exp(-bins/scale) /
(sps.gamma(shape)*scale**shape))
plt.plot(bins, y, linewidth=2, color='r')
plt.show()
I find that the following code takes a very long time and the pop-up figure window becomes non-responding.
"y = bins**(shape-1)*(np.exp(-bins/scale)/(sps.gamma(shape)*scale**shape))"
If I remove the lower and upper bounds for the gamma distribution, it runs very fast.
Any help would be appreciated.