Is there a way, using some established Python package (e.g. SciPy) to define my own probability density function (without any prior data, just $f(x) = a x + b$), so I can then make calculations with it (such as obtaining the variance of the continuous random variable)? Of course I could take, say, SymPy or Sage, create a symbolic function and do the operations, but I'm wondering whether instead of doing all this work myself I can make use of an already-implemented package.
You have to subclass the rv_continuous class in scipy.stats
import scipy.stats as st class my_pdf(st.rv_continuous): def _pdf(self,x): return 3*x**2 # Normalized over its range, in this case [0,1] my_cv = my_pdf(a=0, b=1, name='my_pdf')
now my_cv is a continuous random variable with the given PDF and range [0,1]
Note that in this example
my_cv are arbitrary names (that could have been anything), but
_pdf is not arbitrary; it and
_cdf are methods in
st.rv_continuous one of which must be overwritten in order for the subclassing to work.
You should check out sympy.stats. It provides an interface to deal with random variables. The following example provides a random variable
X defined on the unit interval with density
In : from sympy.stats import * In : x = Symbol('x') In : X = ContinuousRV(x, 2*x, Interval(0, 1)) In : P(X>.5) Out: 0.750000000000000 In : Var(X) # variance Out: 1/18 In : E(2*cos(X)+X**2) # complex expressions are ok too Out: -7/2 + 4⋅cos(1) + 4⋅sin(1)
If you're interested this abstraction can handle some fairly complex manipulations.