Search code examples
pythonsympyprobability

Expected value with symbolic probabilities in SymPy


I'd like to find the expected value of a discrete random variable without specifying a particular distribution so I can still manipulate the entire expression symbolically.

For example, how would I get the rhs of the following expectation using summation in sympy?

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


Solution

  • If n is unknown, you can use 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
    

    If n is known, you'll probably want to just represent the actual sum:

    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))