Reputation: 121
I'm using sympy to do symbolic calculations in Python3. My problem is to enforce a substitution of a known term a, defined as a product of x, y and z. See this minimal example:
import sympy as sp
from sympy.abc import a,x,y,z
expr=(x*y)/z**3 *(x**2*y**2-5*x*y*z+12*z**2)
print (expr) #as typed in line 3
print (expr.subs(x*y/z,a)) #only substitues the first factor to a**1/z**2
print (sp.simplify(expr)) #not any better
What I'd like to see is an expression of the form
a**3-5*a**2+12*a
with a=x*y/z Neither line 4 nor lines 5 or 6 do the trick. Can anyone help me? Thank you!
Upvotes: 2
Views: 254
Reputation: 1869
Use expand first:
In [13]: expr.expand()
Out[13]:
3 3 2 2
x ⋅y 5⋅x ⋅y 12⋅x⋅y
───── - ─────── + ──────
3 2 z
z z
In [14]: expr.expand().subs({x * y / z: a})
Out[14]:
3 2
a - 5⋅a + 12⋅a
Upvotes: 1
Reputation: 594
Well, for this particular example, the following idea leads to a solution, but in more generality, I don't know how to achieve the goal.
So, instead of substituting x*y/z
as a
, substitute equivalently x*y
to a*z
, and then simplify.
expr2 = expr.subs(x*y, a*z)
print(expr2)
print(sp.simplify(expr2))
Upvotes: 1