How to create a random variable whose parameters are themselves random variables in SymPy?

*爱你&永不变心* 提交于 2019-12-10 23:01:32

问题


I have a random variable Y whose distribution is Poisson with parameter that is itself a random variable X, which is Poisson with parameter 10.

How can I use SymPy to automatically calculate the covariance between X and Y? The code

from sympy.stats import *
x1 = Poisson("x1", 3)
x2 = Poisson("x2", x1)
print(covariance(x2,x1))

raises an error ValueError: Lambda must be positive The documentation is not clear to me on this matter, and playing around with the function given did not seem to work.


回答1:


This kind of manipulation is not implemented in SymPy. But you can pass a symbol (z1 below) for the parameter of a distribution. Then after the first step of computation, replace z1 by x1 and take expected value.

from sympy import Symbol
from sympy.stats import Poisson, E
z1 = Symbol("z1")
x1 = Poisson("x1", 3)
x2 = Poisson("x2", z1)
Ex2 = E(E(x2).subs(z1, x1))
Vx2 = E(E((x2-Ex2)**2).subs(z1, x1))
cov = E(E((z1-E(x1))*(x2-Ex2)).subs(z1, x1))
print("E(x2) = {}, var(x2) = {}, cov(x1, x2) = {}".format(Ex2, Vx2, cov))

Output:

E(x2) = 3, var(x2) = 6, cov(x1, x2) = 3

Notice the appearance of Ex2 instead of E(x2) in the formulas for variance and covariance. Using E(x2) here would give incorrect results because E(x2) is an expression involving z1. For the same reason I'm not using variance or covariance functions (as they'd involve the variable E(x2) instead of the correct value 3), expressing everything explicitly as an expected value.



来源:https://stackoverflow.com/questions/45237209/how-to-create-a-random-variable-whose-parameters-are-themselves-random-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!