In [1]:
%pylab inline
In [12]:
import scipy.stats as stats
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as rnd
# distribution truncated to:
trunc_start = -1
trunc_end = 2
#plot the original distribution
xrng=np.arange(-10,10,.1)
yrng=stats.logistic.pdf(xrng)
plt.plot(xrng,yrng)
#plot the truncated distribution
nrm=stats.logistic.cdf(trunc_end)-stats.logistic.cdf(trunc_start)
xrng=np.arange(trunc_start,trunc_end,.01)
yrng=stats.logistic.pdf(xrng)/nrm
plt.plot(xrng,yrng)
#sample using the inverse cdf
yr=rnd.rand(100000)*(nrm)+stats.logistic.cdf(trunc_start)
xr=stats.logistic.ppf(yr)
plt.hist(xr,normed=True)
plt.show()