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...

  1. Let's import SymPy and the stats module:
    >>> from sympy import *
        from sympy.stats import *
        init_printing()
  2. Let's roll two dice, X and Y, with six faces each:
    >>> X, Y = Die('X', 6), Die('Y', 6)
  3. We can compute probabilities defined by equalities (with the Eq operator) or inequalities:
    >>> P(Eq(X, 3))
    How to do it...
    >>> P(X > 3)
  4. Conditions ...

Get IPython Interactive Computing and Visualization Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.