# How to separate a symbolic expression into sub expressions

I want to separate a symbolic expression into two sub-expressions, one sub-expression with a certain variable and the other without the variable.

The following example was revised to better demonstrate what I want to achieve

For example, with the following function, f,

var('x,y,z')
f=cos(x)*e^(cos(x))*(3*y+z)^2


I want to obtain two sub-expressions as

f1=cos(x)*e^(cos(x))
f2=(3*y+z)^2

edit retag close merge delete

Sort by » oldest newest most voted

In this particular example, you can do:

sage: f1,f2 = f.operands()
sage: f1
(3*y + 2)^2
sage: f2
cos(x)


But it is not clear what do you expect with, for example exp(cos(x)*(3*y+2)^2) ? What do you mean by "separate" ? Is it only about the principal product ?

EDIT: according to your precisions: first you have to know whether the top-level operation is a product.

sage: from sage.symbolic.operators import mul_vararg
sage: f.operator() == mul_vararg
True


Then, you have to group the operands that contain only the variable x, and those that do not contain the variable x (if, again, i uinderstand correctly your comment): for this you have to inspect, for each operand of the top-level product, if its variables is equal to (x,) of if it does not contain x.

Putting everything together gives:

sage: def separate(f):
sage:     from sage.symbolic.operators import mul_vararg
sage:     if f.operator() == mul_vararg:
sage:         xonly = []
sage:         nox = []
sage:         for term in f.operands():
sage:             if term.variables() == (x,):
sage:                 xonly.append(term)
sage:             elif x not in term.variables():
sage:                 nox.append(term)
sage:             else:
sage:                 raise ValueError("There is a term that mixes x and other variables!")
sage:         return (prod(xonly), prod(nox))
sage:     else:
sage:         raise ValueError("Not a product!")


Then, you can check on various examples:

sage: var('x,y,z')
(x, y, z)
sage: f=cos(x)*e^(cos(x))*(3*y+z)^2
sage: separate(f)
(cos(x)*e^cos(x), (3*y + z)^2)

sage: separate(x*log(y+z)*x^2*sin(x))
(x^3*sin(x), log(y + z))

sage: separate(x*log(y+x)*x^2)
ValueError: There is a term that mixes x and other variables!

sage: separate(x*log(y+x)*x^2)
ValueError: There is a term that mixes x and other variables!

sage: separate(log(x))
ValueError: Not a product!

more

I should have put a more well-thought example out. My function is separable; i.e., f=f1(x)*f2(y,z,.....). What I want is to extract the f1(x) part and then run numerical integration of f1 over x.