Created
June 3, 2012 17:49
-
-
Save josef-pkt/2864348 to your computer and use it in GitHub Desktop.
Random variable by subclassing distribution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
"""Random variable by subclassing distribution | |
Created on Sun Jun 03 10:43:04 2012 | |
Author: Josef Perktold | |
adjusted example from mailing list | |
generic random number generation given only the pdf is slooooow | |
time 10.9979999065 0.0 | |
""" | |
import numpy as np | |
from scipy import stats | |
class MyDist1(stats.rv_continuous): | |
def _pdf(self,x): | |
return x*x * 1.5 | |
d1 = MyDist1(name='pdf dist', a=-1, b=1) | |
print "check integral" | |
print d1.cdf([-1+1e-15, -0.99, 0.99, 1-1e-15]) | |
rvs1 = d1.rvs(size=100) | |
#array([-0.37491512, -0.98326919, 0.97390905, 0.89196531, -0.96708172, | |
# 0.93946045, -0.73901588, 0.52395328, 0.93735005, 0.37665337]) | |
class MyDist2(stats.rv_continuous): | |
def _pdf(self,x): | |
return x*x * 3.0 / 2.0 | |
def _ppf(self, q): | |
tmp = 2.*q - 1. | |
sgn = np.sign(tmp) | |
return sgn * np.power(np.abs(tmp), 1./3) | |
d2 = MyDist2(name='ppf dist', a=-1, b=1) | |
rvs2 = d2.rvs(size=100) | |
print "\nks test" | |
print stats.ks_2samp(rvs1, rvs2) | |
print "\nsame ppf" | |
qq = np.linspace(1e-10, 1.-1e-10, 5) | |
print d1.ppf(qq) | |
print d2.ppf(qq) | |
import time | |
t0 = time.time() | |
d1.rvs(size=10000) | |
t1 = time.time() | |
d2.rvs(size=10000) | |
t2 = time.time() | |
print "\ntime", t1-t0, t2-t1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment