Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify conditional integrals in SymPy

In SymPy, if I integrate a general Gaussian by:

x = Symbol("x", real=True)
y = Symbol("y", real=True)
s = Symbol("s", real=True)

gaussian = exp(-((x-y)**2)/(2*(s**2)))
nfactor = simplify(integrate(gaussian, (x,-oo,oo)))

I get nfactor as Piecewise dependent on periodic_argument and polar_lift. A object the same as made by:

Abs(periodic_argument(polar_lift(s)**(-2), oo))

must be less than pi/2 for the solution I want. Is there a nice way to only have this condition - in Mathematica one might use Assuming and Refine or Simplify, but I'm new to sympy and I don't know what to do here.

like image 832
Lucas Avatar asked Feb 17 '23 12:02

Lucas


1 Answers

Setting s to be positive should be enough. Really, I think the answer should be in terms of Abs(s), since for real s, sqrt(s**2) = Abs(s) (I'm not positive about that, though).

In the git master branch of SymPy, you can use refine to manually assume the exact condition you want

In [6]: refine(nfactor, Q.is_true(Abs(periodic_argument(1/polar_lift(s)**2, oo)) <= pi/2))
Out[6]:
  ___   ___
╲╱ 2 ⋅╲╱ π ⋅s

Another way, if you know that your integral satisfies the conditions, but you can't get them to simplify (because unfortunately, simplification of such conditions in SymPy is very poor), you can just use integrate(conds='none'), or integrate(conds='separate') (this does not require the git version to work.

In [8]: integrate(gaussian, (x,-oo,oo), conds='none')
Out[8]:
  ___   ___
╲╱ 2 ⋅╲╱ π ⋅s

In [9]: integrate(gaussian, (x,-oo,oo), conds='separate')
Out[9]:
⎛  ___   ___    │                 ⎛      1          ⎞│   π⎞
⎜╲╱ 2 ⋅╲╱ π ⋅s, │periodic_argument⎜──────────────, ∞⎟│ ≤ ─⎟
⎜               │                 ⎜          2      ⎟│   2⎟
⎝               │                 ⎝polar_lift (s)   ⎠│    ⎠

You can also just pull it out of the Piecewise

In [10]: nfactor.args[0][0]
Out[10]:
  ___   ___
╲╱ 2 ⋅╲╱ π ⋅s

The preferred way, of course, will be to use refine, but unfortunately, things using the new assumptions system (anything using Q) are still in development, so may not work yet, or may only work in the SymPy development version.

like image 153
asmeurer Avatar answered Feb 26 '23 18:02

asmeurer