Search code examples
pythonscipystatisticsprobabilityprobability-density

Loading additional parameters to scipy's rv_continuous


I am planning to do some basic algebra on continuous, non-analytical random variabels. I want to define their probability density functions as arrays x and f(x).

Yet, I was surprised to find out that there does not seem to be any package that does basic operations like computing sum- or product distributions of two pdfs (please correct me if I'm wrong). To implement those operations by myself, I then planned to create a subclass of scipy.stats rv_continuous, following this thread:

import scipy as sp
import numpy as np

class my_pdf(sp.stats.rv_continuous):
    def __init__(self,x,p):
        self.x = x
        self.p = p

    def _pdf(self,x):
        return sp.interpolate.interp1d(self.x,self.p)(x)

x = np.linspace(0,1,101)
f = 3*x**2
my_cv = my_pdf(x,f)
my_cv.pdf(0)

The last line throws an error, because overwriting the init method is probably not the way to go. Is there a way to pass additional parameters to rv_continuous, or another way to approach the problem, other than building everything from scratch?


Solution

  • This seems to work for me:

    import scipy as sp
    import scipy.stats
    import numpy as np
    
    class my_pdf(sp.stats.rv_continuous):
        def __init__(self,x,p):
            super().__init__(a=x.min(), b=x.max())
            self.x = x
            self.p = p
        
        def _pdf(self,x):
            return sp.interpolate.interp1d(self.x,self.p)(x)
    
    x = np.linspace(0,1,101)
    f = 3*x**2
    my_cv = my_pdf(x,f)
    my_cv.pdf(0)
    my_cv.cdf(0.5)