Instantly share code, notes, and snippets.

# josef-pkt/try_distr_rvs.py Created Jun 3, 2012

Random variable by subclassing distribution
 # -*- 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