Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36793

Conditional expectation with sympy

How can I calculate the conditional expectation of a random variable in sympy? I read this and tried:

from sympy.stats import *
v = Uniform("v",0,1)
E(v)

this returns correctly 1/2, but then:

E(v, v>1/2)

returns NaN. I also tried:

E(v, where(v > 1/2))

it returned 1/2, which is incorrect (it should be 3/4).

What am I doing wrong?

Upvotes: 2

Views: 648

Answers (1)

user6655984
user6655984

Reputation:

This issue (which I see you already reported) is specific to uniformly distributed random variables. (There's also an older issue involving Uniform.) For other distributions, what you did works correctly:

>>> from sympy.stats import *
>>> x = Exponential("x", 1)
>>> E(x, x < 2)
-3/(-1 + exp(2)) + exp(2)/(-1 + exp(2))

As for the uniform type, a workaround for now is to remember that conditioning a uniformly distributed random variable to some interval creates another uniformly distributed random variable.

So the value of E(v, v > 1/2) can be found by computing

E(Uniform("x", 1/2, 1))

which returns 0.75.


Caution: if working interactively, one may want to eventually import from core SymPy, in addition to its stats module. Since E stands for Euler's number 2.718... in SymPy, one may end up unable to compute expectations with

TypeError: 'Exp1' object is not callable

So one either has to be more specific about what to import, or use namespace for one or both modules. My preferred solution is

from sympy import *
import sympy.stats as st

So that st.E is expectation while E is 2.718...

Upvotes: 2

Related Questions