[SciPy-User] scipy.stats: Sampling from an arbitrary probability distribution
Nathaniel Smith
njs@pobox....
Sun Jun 3 09:18:20 CDT 2012
On Sun, Jun 3, 2012 at 12:20 PM, Daniel Sabinasz
<d.sabinasz@googlemail.com> wrote:
> Hi all,
>
> I need to sample a random number from a distribution whose probability
> density function I specify myself. Is that possible using scipy.stats?
>
> Here is what I have already:
>
> import scipy.stats as st
>
> class my_pdf(st.rv_continuous):
> def _pdf(self,x):
> return x*x/10.0
>
> my_cv = my_pdf(name='my_pdf')
>
> Can I now somehow sample a random number from my_cv?
The easiest and fastest way to generate random variates from a given
distribution is to calculate the quantile function and then feed it
random samples from the uniform distribution[1]. The catch is that
computing the quantile function requires that you be able to calculate
the integral of your PDF (the CDF), and then invert the CDF, so this
method only applies for PDFs for which this is possible. But if your
PDF is really as simple as the one in your example then this is a good
approach :-).
[1] https://en.wikipedia.org/wiki/Inverse_transform_sampling
-- Nathaniel
More information about the SciPy-User
mailing list