确定 SymPy 表达式的各个项
对于我正在从事的项目,我必须从任意 SymPy 表达式中选择特定术语。为此,我使用 .args
如果表达式包含多个不同的项,它可以正常工作,但如果仅存在单个项,则返回项中的各个系数。请参阅以下示例:
import sympy as sym
x, c0, c1 = sym.symbols('x c0 c1')
f0 = c0*x
f1 = c1*x**2
f2 = c0*x + c1*x**2
print(f0.args) # Output: (c0, x) Desired: (c0*x)
print(f1.args) # Output: (c1, x**2) Desired: (c1*x**2)
print(f2.args) # Output: (c0*x, c1*x**2)
此方法的工作原理与我希望的 f2
一样,它返回 (c0*x, c1*x**2)
。然而,对于f0
和f1
,它分别返回系数c0、c1
和x
。对于单项表达式,系数和 x 也作为乘法表达式返回,我将如何实现所需的输出?
请注意,理想情况下,我希望此方法适用于任何形式的表达式,并且任意依赖于 x 和任意数量的系数。
For a project I am working on I have to select a specific term from an arbitrary SymPy expression. For this I am using .args
which works fine if the expression consists of multiple distinct terms, but returns the individual coefficients in the term if only a single term is present. See the following example:
import sympy as sym
x, c0, c1 = sym.symbols('x c0 c1')
f0 = c0*x
f1 = c1*x**2
f2 = c0*x + c1*x**2
print(f0.args) # Output: (c0, x) Desired: (c0*x)
print(f1.args) # Output: (c1, x**2) Desired: (c1*x**2)
print(f2.args) # Output: (c0*x, c1*x**2)
This method works as I would want it to for f2
, where it returns (c0*x, c1*x**2)
. For f0
and f1
however it returns the coefficients c0, c1
and x
separately. How would I go achieving the desired output where for the single term expressions the coefficients and x
are also returned as a multiplicative expression?
Note that ideally I would want this method to work for any form of expression, with arbitrary dependencies on x
and an arbitrary amount of coefficients.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
功劳归于奥斯卡·本杰明。由于我无法接受他们的评论作为答案,因此我将其重新发布到此处,同时还提供了一个具体的示例。
“您可以使用
Add.make_args(f0)
”这将如下所示:
它将返回:
Credit goes to Oscar Benjamin. Since I can't accept their comment as the answer I am reposting it here while also providing a concrete example.
"You can use
Add.make_args(f0)
"This would then look like this:
Which would return:
您需要使用
poly
来说明您有多项式:返回
以获取单项式,只需使用
which给出
You need to use
poly
to state the fact that you have polynomials:returns
to get the monimials, simply use
which gives