Computing exact probabilities and manipulating random variables
SymPy includes a module named stats
that lets us create and manipulate random variables. This is useful when we work with probabilistic or statistical models; we can compute symbolic expectancies, variances probabilities, and densities of random variables.
How to do it...
- Let's import SymPy and the stats module:
In [1]: from sympy import * from sympy.stats import * init_printing()
- Let's roll two dice,
X
andY
, with six faces each:In [2]: X, Y = Die('X', 6), Die('Y', 6)
- We can compute probabilities defined by equalities (with the
Eq
operator) or inequalities:In [3]: P(Eq(X, 3)) Out[3]: 1/6 In [4]: P(X>3) Out[4]: 1/2
- Conditions can also involve multiple random variables:
In [5]: P(X>Y) Out[5]: 5/12
- We can compute conditional probabilities:
In [6]: P(X+Y>6, X<5) Out[6]: 5/12
- We can also work with arbitrary discrete or continuous random variables:
In [7]: Z = Normal('Z',...