Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factoring a SymPy expression into groups that involve one symbol only

Suppose I have an expression in sympy that only consists of a single term. This expression either has subexpressions that depend on a symbol x, on a symbol y, or on neither x nor y. I would like sympy to return three expressions, the first depends only on x, the second only on y, and the third on neither, such that the product of the three expressions is the original expression. E.g.

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

should return x^2 * cos(x) and 1/sin(y)/y and 2. Is this possible?

like image 844
dbrane Avatar asked Oct 27 '25 04:10

dbrane


1 Answers

Assuming you have a single term expr made up by multiplying terms in x, y and other symbols or constants you can do something like below:

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

Is this as you wanted?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!