#243 · Probability · Medium
⊣ Solve on deep-ml.comCompute the covariance of two discrete random variables given their joint probability mass function (PMF).
def covariance_from_joint_pmf(
x_values: list[float],
y_values: list[float],
joint_pmf: list[list[float]],
) -> float:
"""
x_values: possible values of X
y_values: possible values of Y
joint_pmf: [len(x_values), len(y_values)] where joint_pmf[i][j] = P(X=x_i, Y=y_j)
"""
# E[X]
e_x = 0.0
for i, x in enumerate(x_values):
marginal_x = sum(joint_pmf[i][j] for j in range(len(y_values)))
e_x += x * marginal_x
# E[Y]
e_y = 0.0
for j, y in enumerate(y_values):
marginal_y = sum(joint_pmf[i][j] for i in range(len(x_values)))
e_y += y * marginal_y
# E[XY]
e_xy = 0.0
for i, x in enumerate(x_values):
for j, y in enumerate(y_values):
e_xy += x * y * joint_pmf[i][j]
# Cov(X, Y) = E[XY] - E[X]E[Y]
cov = e_xy - e_x * e_y
return round(cov, 6)