Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 20: Symbolic Probability with SymPy

Welcome to Chapter 20! Throughout this book, we’ve used NumPy and SciPy for numerical computation – calculating probabilities as decimal approximations, simulating random processes, and plotting distributions. This numerical approach is powerful and practical for most real-world applications.

However, there’s another way to work with probability: symbolic computation. Instead of getting 0.16666... when calculating the probability of rolling a 1 on a fair die, we can get the exact answer: 1/6. Instead of numerically evaluating integrals or derivatives, we can manipulate formulas algebraically.

This chapter introduces SymPy (Symbolic Python), a Python library for symbolic mathematics. SymPy allows us to:

Learning Objectives

Why Symbolic Computation?

Numerical vs Symbolic Approaches

Throughout this book, we’ve primarily used the numerical approach:

Numerical result: 0.31249999999999983
As decimal: 0.3125000000

The numerical approach gives us a floating-point approximation. For most practical purposes, this is perfect! But what if we want the exact answer?

Symbolic result: 5/16
Simplified: 5/16
As decimal: 0.3125

When to Use Each Approach

Use Numerical (NumPy/SciPy) when:

Use Symbolic (SymPy) when:

Best practice: Start with symbolic to understand the mathematics, then use numerical for computation.

SymPy Basics for Probability

Exact Numbers: Rational vs Float

Floating point (numerical):
  1/3 = 0.3333333333333333
  1/3 + 1/3 + 1/3 = 1.0

Rational (symbolic):
  1/3 = 1/3
  1/3 + 1/3 + 1/3 = 1

This exact arithmetic is crucial for probability calculations!

Symbolic Combinatorics

SymPy provides symbolic versions of the combinatorial functions we’ve been using:

=== Factorials ===
math.factorial(10) = 3628800
sp.factorial(10) = 3628800

Symbolic: n! = factorial(n)

=== Permutations ===
scipy perm(10, 3) = 720
SymPy P(10, 3) = 720

=== Combinations ===
scipy comb(10, 3) = 120
SymPy C(10, 3) = 120

Symbolic: C(n, k) = binomial(n, k)

Simplifying Expressions

One of SymPy’s superpowers is simplifying complex expressions:

Binomial PMF:
  Original: p**k*(1 - p)**(-k + n)*binomial(n, k)
  Expanded: p**k*(1 - p)**(-k + n)*binomial(n, k)

Sum of probabilities (n=3): 1

Symbolic Random Variables with sympy.stats

The sympy.stats module lets us work with random variables symbolically, similar to how we used scipy.stats numerically.

Discrete Distributions

=== Die Probabilities ===
P(X = 3) = 0
P(X > 4) = 1/3
P(X is even) = 0

E(X) = 7/2
Var(X) = 35/12
=== Binomial(10, 1/2) ===
P(X = 5) = 0
P(X <= 3) = 11/64
E(X) = 5
Var(X) = 5/2

=== Binomial(n, p) - Symbolic ===
E(X) = Sum(Piecewise((_k*p**_k*(1 - p)**(-_k + n)*binomial(n, _k), _k <= n), (0, True)), (_k, 0, n))
Var(X) = Sum(Piecewise((p**_k*(1 - p)**(-_k + n)*(_k - Sum(Piecewise((_k*p**_k*(1 - p)**(-_k + n)*binomial(n, _k), _k <= n), (0, True)), (_k, 0, n)))**2*binomial(n, _k), _k <= n), (0, True)), (_k, 0, n))

=== Geometric(1/6) - First success ===
P(X = 1) = 0
P(X = 6) = 0
E(X) = 6
Var(X) = 30

Continuous Distributions

=== Normal(μ, σ) - Symbolic ===
E(X) = mu
Var(X) = sigma**2

=== Standard Normal(0, 1) ===
E(Z) = 0
Var(Z) = 1

=== Normal(100, 15) ===
P(X > 115) = sqrt(2)*(-sqrt(2)*sqrt(pi)*erf(sqrt(2)/2) + sqrt(2)*sqrt(pi))/(4*sqrt(pi))
=== Exponential(λ=1/2) ===
E(X) = 2
Var(X) = 4

=== Exponential(λ) - Symbolic ===
E(X) = 1/lambda
Var(X) = lambda**(-2)

Deriving Probability Formulas

One of the most powerful uses of SymPy is deriving and verifying probability formulas.

Moment Generating Functions

=== Binomial MGF ===
M(t) = (p*exp(t) - p + 1)**n

M'(t) = n*p*(p*exp(t) - p + 1)**n*exp(t)/(p*exp(t) - p + 1)
E(X) = M'(0) = n*p

M''(0) = n*p*(n*p - p + 1)
Var(X) = E(X²) - E(X)² = n*p*(1 - p)

Bayes’ Theorem Symbolically

=== Bayes' Theorem ===
P(A|B) = P(A)*P(B|A)/P(B)

=== Medical Test Example ===
P(Disease) = 1/100
P(Positive|Disease) = 19/20
P(Positive|No Disease) = 1/10
P(Positive) = 217/2000 = 0.1085
P(Disease|Positive) = 19/217 = 0.0876

Converting Between Symbolic and Numerical

Symbolic: P(X=5) = 0
Exact fraction: 0
As float: 0.0
SciPy numerical: 0.17886305056987964
Difference: 0.17886305056987964

Symbolic E(X) = 6 = 6.0
SciPy E(X) = 6.0

Practical Examples

Example 1: Exact Poker Probabilities

Total 5-card hands: 2598960
Ways to get full house: 3744
Probability (exact): 6/4165
Probability (decimal): 0.001441
Odds: 1 in 694.17

Example 2: Birthday Problem - Exact Solution

n=10: P(at least 2 share) = 0.116948
n=20: P(at least 2 share) = 0.411438
n=23: P(at least 2 share) = 0.507297
n=30: P(at least 2 share) = 0.706316
n=50: P(at least 2 share) = 0.970374

Exact probability for n=23: 0.5072972343
Greater than 50%? True

Example 3: Deriving Variance Formula

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[16], line 15
     11                     5: sp.Rational(1,6),
     12                     6: sp.Rational(1,6)})
     13 
     14 # Method 1: Using variance function
---> 15 var_direct = variance(X)
     16 
     17 # Method 2: E(X²) - E(X)²
     18 E_X = E(X)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/rv_interface.py:80, in variance(X, condition, **kwargs)
     77     from sympy.stats.symbolic_probability import Variance
     78     return Variance(X, condition)
---> 80 return cmoment(X, 2, condition, **kwargs)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/rv_interface.py:242, in cmoment(X, n, condition, evaluate, **kwargs)
    240 from sympy.stats.symbolic_probability import CentralMoment
    241 if evaluate:
--> 242     return CentralMoment(X, n, condition).doit()
    243 return CentralMoment(X, n, condition).rewrite(Integral)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/symbolic_probability.py:688, in CentralMoment.doit(self, **hints)
    687 def doit(self, **hints):
--> 688     return self.rewrite(Expectation).doit(**hints)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/symbolic_probability.py:260, in Expectation.doit(self, **hints)
    257 evaluate = hints.get('evaluate', True)
    259 if deep:
--> 260     expr = expr.doit(**hints)
    262 if not is_random(expr) or isinstance(expr, Expectation):  # expr isn't random?
    263     return expr

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/core/basic.py:1947, in Basic.doit(self, **hints)
   1928 """Evaluate objects that are not evaluated by default like limits,
   1929 integrals, sums and products. All objects of this kind will be
   1930 evaluated recursively, unless some species were excluded via 'hints'
   (...)   1944 
   1945 """
   1946 if hints.get('deep', True):
-> 1947     terms = [term.doit(**hints) if isinstance(term, Basic) else term
   1948                                  for term in self.args]
   1949     return self.func(*terms)
   1950 else:

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/core/basic.py:1947, in <listcomp>(.0)
   1928 """Evaluate objects that are not evaluated by default like limits,
   1929 integrals, sums and products. All objects of this kind will be
   1930 evaluated recursively, unless some species were excluded via 'hints'
   (...)   1944 
   1945 """
   1946 if hints.get('deep', True):
-> 1947     terms = [term.doit(**hints) if isinstance(term, Basic) else term
   1948                                  for term in self.args]
   1949     return self.func(*terms)
   1950 else:

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/core/operations.py:478, in AssocOp.doit(self, **hints)
    476 def doit(self, **hints):
    477     if hints.get('deep', True):
--> 478         terms = [term.doit(**hints) for term in self.args]
    479     else:
    480         terms = self.args

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/core/operations.py:478, in <listcomp>(.0)
    476 def doit(self, **hints):
    477     if hints.get('deep', True):
--> 478         terms = [term.doit(**hints) for term in self.args]
    479     else:
    480         terms = self.args

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/core/operations.py:478, in AssocOp.doit(self, **hints)
    476 def doit(self, **hints):
    477     if hints.get('deep', True):
--> 478         terms = [term.doit(**hints) for term in self.args]
    479     else:
    480         terms = self.args

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/core/operations.py:478, in <listcomp>(.0)
    476 def doit(self, **hints):
    477     if hints.get('deep', True):
--> 478         terms = [term.doit(**hints) for term in self.args]
    479     else:
    480         terms = self.args

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/symbolic_probability.py:288, in Expectation.doit(self, **hints)
    286     return self.func(expr)
    287 # Otherwise case is simple, pass work off to the ProbabilitySpace
--> 288 result = pspace(expr).compute_expectation(expr, evaluate=evaluate)
    289 if hasattr(result, 'doit') and evaluate:
    290     return result.doit(**hints)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/drv.py:313, in SingleDiscretePSpace.compute_expectation(self, expr, rvs, evaluate, **kwargs)
    311 x = self.value.symbol
    312 try:
--> 313     return self.distribution.expectation(expr, x, evaluate=evaluate,
    314             **kwargs)
    315 except NotImplementedError:
    316     return Sum(expr * self.pdf, (x, self.set.inf, self.set.sup),
    317             **kwargs)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/drv.py:160, in SingleDiscreteDistribution.expectation(self, expr, var, evaluate, **kwargs)
    156 p = poly(expr, var)
    158 t = Dummy('t', real=True)
--> 160 mgf = self.moment_generating_function(t)
    161 deg = p.degree()
    162 taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/drv.py:123, in SingleDiscreteDistribution.moment_generating_function(self, t, **kwargs)
    121     if mgf is not None:
    122         return mgf
--> 123 return self.compute_moment_generating_function(**kwargs)(t)

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/core/cache.py:72, in __cacheit.<locals>.func_wrapper.<locals>.wrapper(*args, **kwargs)
     69 @wraps(func)
     70 def wrapper(*args, **kwargs):
     71     try:
---> 72         retval = cfunc(*args, **kwargs)
     73     except TypeError as e:
     74         if not e.args or not e.args[0].startswith('unhashable type:'):

File /opt/hostedtoolcache/Python/3.11.18/x64/lib/python3.11/site-packages/sympy/stats/drv.py:112, in SingleDiscreteDistribution.compute_moment_generating_function(self, **kwargs)
    110 x = Dummy('x', integer=True)
    111 pdf = self.pdf(x)
--> 112 mgf = summation(exp(t*x)*pdf, (x, self.set.inf, self.set.sup))
    113 return Lambda(t, mgf)

TypeError: unsupported operand type(s) for *: 'exp' and 'Dict'

Working with Joint Distributions

Limitations and Performance Considerations

While SymPy is powerful, it has limitations:

Key takeaways:

Summary

In this chapter, we explored symbolic probability computation with SymPy:

Key Concepts:

When to Use SymPy:

When to Use NumPy/SciPy:

Best Practice: Use SymPy to understand the mathematics, then use NumPy/SciPy for practical computation.

In the next chapter, we’ll explore SageMath, a comprehensive mathematical software system that combines the power of SymPy, NumPy, and many other tools into a unified environment.

Exercises

  1. Exact Coin Flips: Calculate the exact probability of getting exactly 7 heads in 10 fair coin flips using SymPy. Compare with SciPy.

  2. Symbolic Variance: Create a symbolic random variable following a Poisson distribution with parameter λ. Derive E(X) and Var(X) symbolically.

  3. Poker Hands: Calculate the exact probability of getting a “straight flush” (5 consecutive cards of the same suit) in 5-card poker.

  4. Conditional Probability: Using two symbolic dice X and Y, calculate P(X = 4 | X + Y = 9) exactly.

  5. MGF Derivation: Derive the moment generating function for a Geometric distribution with parameter p, and use it to find E(X) and Var(X).

  6. Birthday Problem Extension: Modify the birthday problem to find the smallest group size where P(at least 2 share) > 0.9.

  7. Bayes Update: A rare disease affects 0.1% of the population. A test is 99% accurate (both sensitivity and specificity). If you test positive, what’s the exact probability you have the disease?

  8. Sum of Uniforms: Create two independent discrete uniform random variables on {1,2,3,4,5,6}. Find the exact PMF of their sum.

Further Reading