Book Image

IPython Interactive Computing and Visualization Cookbook

By : Cyrille Rossant
Book Image

IPython Interactive Computing and Visualization Cookbook

By: Cyrille Rossant

Overview of this book

Table of Contents (22 chapters)
IPython Interactive Computing and Visualization Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

    In [1]: from sympy import *
            from sympy.stats import *
            init_printing()
  2. Let's roll two dice, X and Y, with six faces each:

    In [2]: X, Y = Die('X', 6), Die('Y', 6)
  3. 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
  4. Conditions can also involve multiple random variables:

    In [5]: P(X>Y)
    Out[5]: 5/12
  5. We can compute conditional probabilities:

    In [6]: P(X+Y>6, X<5)
    Out[6]: 5/12
  6. We can also work with arbitrary discrete or continuous random variables:

    In [7]: Z = Normal('Z', 0, 1)  # Gaussian variable
    In [8]: P(Z&gt...