Reputation: 2063
I want to substitute expression
(k*x_2 + m)/(x_2 + 1) + (k*x_1 + m)/(x_1 + 1)
with
x_1 + x_2 = -(2*k*m-8)/k**2
x_1 * x_2 = m**2/k**2
and simplify it, which should have following result:
8*(k + m)/(k**2 - 2*k*m + m**2 + 8)
I have tried .subs({x1+x2: blahblah, x1*x2: blahblah})
. Indeed, it does substitute some x1+x2
and x1*x2
with blahblah
, but it still remains some x1+x2
in the expression. How to solve this problem?
Thanks!
Upvotes: 2
Views: 1367
Reputation: 19135
Maybe the definition of x1 and x2 had something wrong. I get the desired result using what was shown:
>>> a = (k*x_2 + m)/(x_2 + 1) + (k*x_1 + m)/(x_1 + 1)
>>> b = collect(collect(cancel(a), m), k)
>>> b.subs({x_1 + x_2: -(2*k*m - 8)/k**2, x_1*x_2: m**2/k**2}).simplify()
8*(k + m)/(k**2 - 2*k*m + m**2 + 8)
Another way to think of this problem is that it requires x_1
and x_2
to be eliminated from a
given the relationships you define. So if we solve the coupled relationship for x_1
and x_2
and substitute those into a
we will have the desired result:
>>> e2 # = Eq(x_1 + x_2 , (-2*k*m + 8)/k**2)
x_1 + x_2 == (-2*k*m + 8)/k**2
>>> e3
x_1*x_2 == m**2/k**2
>>> x1x2 = solve((e2,e3),x_1,x_2,dict=True) # two solutions are given
>>> a.subs(x1x2[0]).simplify() # use either solution; the result is the same
8*(k + m)/(k**2 - 2*k*m + m**2 + 8)
Upvotes: 2
Reputation: 91660
SymPy only substitute expressions for expressions if it can find them exactly (with a few little additions like matching 2*x
against 4*x
).
You'll need to rewrite the expression to have those terms like you want. cancel
will put everything under one denominator, and collect
will let you convert m*x_1 + m*x_2
into m*(x_1 + x_2)
in that expression, so that you have x_1 + x_2
. In short:
>>> a = (k*x_2 + m)/(x_2 + 1) + (k*x_1 + m)/(x_1 + 1)
>>> b = collect(collect(cancel(a), m), k)
>>> b
(k*(2*x_1*x_2 + x_1 + x_2) + m*(x_1 + x_2 + 2))/(x_1*x_2 + x_1 + x_2 + 1)
>>> b.subs({x1 + x2: -(2*k*m - 8)/k**2, x1*x2: m**2/k**2})
(k*(2*m**2/k**2 + (-2*k*m + 8)/k**2) + m*(x_1 + x_2 + 2))/(1 + m**2/k**2 + (-2*k*m + 8)/k**2)
This didn't seem to work completely, which I have opened a bug for https://github.com/sympy/sympy/issues/7475.
Upvotes: 0