问题描述
在sympy中,我有一个积分,该积分返回一个逐段对象,例如
In sympy I have an integral which returns a Piecewise object, e.g.
In [2]: from sympy.abc import x,y,z
In [3]: test = exp(-x**2/z**2)
In [4]: itest = integrate(test,(x,0,oo))
In [5]: itest
Out[5]:
⎧ ___
⎪ ╲╱ π ⋅z │ ⎛ 1 ⎞│ π
⎪ ─────── for │periodic_argument⎜──────────────, ∞⎟│ ≤ ─
⎪ 2 │ ⎜ 2 ⎟│ 2
⎪ │ ⎝polar_lift (z) ⎠│
⎪
⎪∞
⎪⌠
⎨⎮ 2
⎪⎮ -x
⎪⎮ ───
⎪⎮ 2
⎪⎮ z
⎪⎮ ℯ dx otherwise
⎪⌡
⎪0
⎩
我只想提取该分段方程式的第一个分支,换句话说,我希望能够执行类似itest.parts(0)
的操作来简单提取sqrt(pi)*z/2
.我似乎找不到任何方法可以执行此操作,但是也许我在文档中使用了错误的搜索词.有什么想法吗?
I would like to extract just the first branch of this piecewise equation, in other words, I would like to be able to do something like itest.parts(0)
to extract simply sqrt(pi)*z/2
. I can't seem to find any way to do this, but perhaps I am using the wrong search terms in the documentation. Any ideas?
修改
仔细研究一下,我设法找到了itest.args[0][0]
可以提取该表达式.但是,这似乎有点骇人听闻.有更好的方法吗?
Poking around a bit, I've managed to find that if I do itest.args[0][0]
I can extract this expression. This seems like a bit of a hack, however. Is there a better approach?
推荐答案
通常,使用.args
是访问表达式各部分的正确方法.
In general, using .args
is the correct way to access parts of an expression.
在这种情况下,integrate
有一个选项,可让您忽略收敛条件
In this case, though, there is an option to integrate
that will let you ignore convergence conditions
In [39]: integrate(test, (x, 0, oo), conds='none')
Out[39]:
___
╲╱ π ⋅z
───────
2
此外,如果您对变量明确设置了已知的假设,则收敛条件通常会自行解决(不过,对于z
的任何简单假设,这种情况似乎都不会发生).例如,如果您知道z
是真实的,请使用z = Symbol('z', real=True)
.通常,如果您知道事情是真实的,或者甚至是积极的,那将有助于确保融合.
Also, if you explicitly set the assumptions that you know on your variables, often the convergence conditions resolve themselves (it doesn't seem to happen in this case for any simple assumptions on z
, though). For example, if you knew that z
was real, use z = Symbol('z', real=True)
. Usually assuming that things are real, or even better positive, when you know it will help a lot in ensuring convergence.
这篇关于处理Sympy积分返回的分段方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!