In sympy, how can I define two random variables, X and Y, that depend on a common condition? For example, how do I solve a problem such as the following:
- We throw a dice. If it falls on 1, then X=1 and Y=0. If it falls on 2, then X=0 and Y=1. Otherwise, X=Y=0. What is the covariance of X,Y?
If X and Y are functions of some Z, then create Z and define X, Y through it. Piecewise
helps with this:
from sympy.stats import *
Z = Die("Z", 6)
X = Piecewise((1, Eq(Z, 1)), (0, True))
Y = Piecewise((1, Eq(Z, 2)), (0, True))
print(covariance(X, Y)) # -1/36
Aside: If Y is a function of X, then create X first and then define Y in terms of it.
from sympy.stats import Bernoulli, covariance
X = Bernoulli("X", 1/6)
Y = 1 - X
print(covariance(X, Y))
Returns -0.138888888888889.