This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
from sympy import * from sympy.stats import * init_printing()
Let's roll two dices X and Y.
X, Y = Die('X', 6), Die('Y', 6)
We can compute probabilities defined by equalities (with the Eq operator) or inequalities...
Conditions can also involve multiple random variables...
We can also work with arbitrary discrete or continuous random variables.
Z = Normal('Z', 0, 1) # Gaussian variable
We can compute expectancies and variances...
as well as densities.
f = density(Z)
This is a lambda function, it can be evaluated on a SymPy symbol:
We can plot this density.
%matplotlib inline plot(f(x), (x, -6, 6));
SymPy.stats works by using integrals and summations for computing probabilistic quantities. For example, P(Z>pi) is:
Eq(Integral(f(x), (x, pi, oo)), simplify(integrate(f(x), (x, pi, oo))))