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:
>>> from sympy import * from sympy.stats import * init_printing()
- Let's roll two dice,
X
andY
, with six faces each:>>> X, Y = Die('X', 6), Die('Y', 6)
- We can compute probabilities defined by equalities (with the
Eq
operator) or inequalities:>>> P(Eq(X, 3))
>>> P(X > 3)
- Conditions can also involve multiple random variables:
>>> P(X > Y)
- We can compute conditional probabilities:
>>> P(X + Y > 6, X < 5)
- We can also work with arbitrary discrete or continuous random variables:
>>> Z = Normal('Z', 0, 1) # Gaussian...