将 SymPy 表达式分解为仅涉及一个符号的组

Factoring a SymPy expression into groups that involve one symbol only

假设我在 sympy 中有一个只包含一个术语的表达式。该表达式的子表达式要么依赖于符号 x,要么依赖于符号 y,要么既不依赖于 x 也不依赖于 y。我想要 sympy return 三个表达式,第一个只依赖于 x,第二个只依赖于 y,第三个都不依赖,这样三个表达式的乘积就是原始表达式。例如

expr = x^2*cos(x)*2/sin(y)/y

应该returnx^2 * cos(x)1/sin(y)/y2。这可能吗?

假设您有一个 expr 项,由 xy 和其他符号或常数相乘组成,您可以执行如下操作:

from sympy import sin, cos, Mul, init_printing
from sympy.abc import x,y

init_printing()
expr = x**2*cos(x)*2/sin(y)/y

def splitXYC(expr):
    xterm = Mul(*[t for t in expr.args if t.has(x)])
    yterm = Mul(*[t for t in expr.args if t.has(y)])
    others = Mul(*[t for t in expr.args if not (t.has(x) or t.has(y)) ])
    return xterm, yterm, others

X,Y,C = splitXYC(expr)
print(X) # Prints x**2*cos(x)
print(Y) # Prints 1/(y*sin(y))
print(C) # Prints 2

这是你想要的吗?

一般来说,这是不可能的:例如,sqrt(x+y)不能分解成x乘以y的函数。但是当可以分解时,as_independent 方法可以帮助找到它:

expr = x**2*cos(x)*2/sin(y)/y
temp, with_x = expr.as_independent(x, as_Mul=True)
const, with_y = temp.as_independent(y, as_Mul=True)
print((with_x, with_y, const))

打印(x**2*cos(x), 1/(y*sin(y)), 2)

使用提示 as_Mul,该方法试图将表达式分离为一个不依赖于给定变量的因子,以及其余的。因此,第一步分离出一个没有 x 的项(称为 temp),第二步从中分离出一个没有 y(常量)的项。

这样的事情也可以用于总和而不是产品,提示 as_Add=True