9
from sympy import *
from sympy.stats import *
mu, Y = symbols('mu Y', real = True, constant = True)
sigma = symbols('sigma', real = True, positive=True)
X = Normal('X', mu, sigma)

When asking for:

E(X, evaluate=False)

I get:

∞                     
⌠                     
⎮                2    
⎮        -(X - μ)     
⎮        ──────────   
⎮              2      
⎮           2⋅σ       
⎮  √2⋅X⋅ℯ             
⎮  ──────────────── dX
⎮       2⋅√π⋅σ        
⌡                     
-∞ 

Which is what I expect. When asking for:

E(X, X>0, evaluate=False)
E(X, X>pi, evaluate=False)
E(X, X >-3, evaluate=False)

Using any constant, the result is as expected from the Normal Definition of conditional expectation. However, when trying to solve for:

E(X, X>Y)

I'm getting an error that has to do with roots. Is there a way to define a Y, such that sympy acknowledges that it is a constant, just like a 0 or a -3 or even pi, and shows the integration as expected? I'm assuming the problem with the request I have from sympy is that somehow the Y isn't acknowledges as a constant and therefore, when trying to solve this request, sympy is faced with a roots problem.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Yevgeniy Loboda
  • 161
  • 1
  • 1
  • 8

1 Answers1

7

Your problem appears to be a limitation in the current inequality solver: the algorithm that transforms a system of inequalities to a union of sets apparently needs to sort the boundary points determined by those inequalities (even if there's only one such point). Reduction of inequalities with symbolic limits has not been implemented yet.

I suggest a dirty trick to get around this limitation. Define:

class SymbolTrick(NumberSymbol):
    def __new__(self, name):
        obj = NumberSymbol.__new__(self)
        obj._name = name
        return obj

    _as_mpf_val = pi._as_mpf_val
    approximation_interval = pi.approximation_interval
    __str__ = lambda self: str(self._name)

This defines a subclass of NumberSymbol having the same numeric value of pi (it is necessary to specify one, as the inequality reduction algorithm needs to sort the list boundaries otherwise it will fail).

At this point:

In [7]: Y = SymbolTrick("Y")

In [8]: E(X, X > Y, evaluate=False)
Out[8]: 
∞                              
⌠                              
⎮                    2         
⎮            -(X - μ)          
⎮            ──────────        
⎮                  2           
⎮               2⋅σ            
⎮      √2⋅X⋅ℯ                  
⎮ ────────────────────────── dX
⎮        ∞                     
⎮        ⌠                     
⎮        ⎮             2       
⎮        ⎮     -(X - μ)        
⎮        ⎮     ──────────      
⎮        ⎮           2         
⎮        ⎮        2⋅σ          
⎮        ⎮ √2⋅ℯ                
⎮ 2⋅√π⋅σ⋅⎮ ────────────── dX   
⎮        ⎮     2⋅√π⋅σ          
⎮        ⌡                     
⎮        Y                     
⌡      
Y
Francesco Bonazzi
  • 1,917
  • 9
  • 10