dimanche 24 septembre 2017

Calculating variance of a simple expression with sympy random variables

Two U(0,1) random variables, X1 and X2, and I want the variance of max(2,X1)+X2.

And I want it using sympy. Yes, I know it's too easy. However, I would like to know if there are built-in ways of handling problems like this one, and how to use them.

>>> from sympy.stats import Uniform, Variance
>>> from sympy import symbols, Integral
>>> X1 = Uniform('X1', 0, 1)
>>> X2 = Uniform('X2', 0, 1)

sympy seems to dislike max; it expresses the same distaste for the if statement.

>>> Variance(max(2, X1) + X2)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "C:\Python34\lib\site-packages\sympy-1.0.1.dev0-py3.4.egg\sympy\core\relational.py", line 195, in __nonzero__
    raise TypeError("cannot determine truth value of Relational")
TypeError: cannot determine truth value of Relational

The problem is trivial, though, and I could simplify it sufficiently.

>>> Variance(2 + X2)
Variance(X2 + 2)
>>> Variance(2 + X2).evaluate_integral()
1/12

I am usually pretty thick unfortunately. How would I handle probability calculations involving conditionals?




Aucun commentaire:

Enregistrer un commentaire