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?
In general, this is impossible: for example, sqrt(x+y)
cannot be separated into a function of x times a function of y. But when factorization is possible, the method as_independent
can help in finding it:
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))
prints (x**2*cos(x), 1/(y*sin(y)), 2)
With the hint as_Mul
, the method is trying to separate the expression into a factor that does not depend on the given variable, and the rest. So, the first step isolates a term without x
(called temp), from which the second step isolates a term without y
(constant).
Such a thing can also be done for sums instead of products, with the hint as_Add=True
.