SymPy中具有符号概率的预期值

时间:2014-06-06 17:09:52

标签: python sympy

我想在不指定特定分布的情况下找到离散随机变量的预期值,这样我仍然可以象征性地操纵整个表达式。

例如,如何在sympy中使用求和得到以下期望的rhs?

http://www.texify.com/img/%5CLARGE%5C%21%5Csum_%7Bi%20%3D%201%7D%5E%7Bn%7D%20P%28a_i%29a_i%20%3D%20P%28a_1%29a_1%20%2B%20...%20%2B%20P%28a_n%29a_n%20.gif

1 个答案:

答案 0 :(得分:1)

如果n未知,您可以使用summation

In [45]: i, n = symbols('i n', integer=True)

In [46]: p, a = symbols('p a', cls=Function)

In [47]: summation(p(a(i))*a(i), (i, 0, n))
Out[47]:
  n
 ___
 ╲
  ╲   a(i)⋅p(a(i))
  ╱
 ╱
 ‾‾‾
i = 0

如果知道n,您可能只想表示实际总和:

In [48]: n = 10

In [49]: sum(p(a(i))*a(i) for i in range(1, n+1))
Out[49]: a(1)⋅p(a(1)) + a(2)⋅p(a(2)) + a(3)⋅p(a(3)) + a(4)⋅p(a(4)) + a(5)⋅p(a(5)) + a(6)⋅p(a(6)) + a(7)⋅p(a(7)) + a(8)⋅p(a(8)) + a(9)⋅p(a(9)) + a(10)⋅p(a(10))