pythonmatlabmathsympyalgebra

Sympy subs does not working for subexpression. Is there a way to solve this?


subs (from sympy library in Python) does not replace a subexpression in all cases except simple ones. MATLAB copes with this task perfectly. Is it possible to somehow achieve the same result as in MATLAB?

Sympy

sympy

MATLAB

matlab


Solution

  • This fails because the product 2*(x + y) automatically expands to the sum of 2x + 2*y, as @hpaulj points out. And @oscarbenjamin points out that re-arranging your substitution so it targets only an atomic part of the expression you desire to replace will work.

    In addition, if you backsubstitute to restore the original atom you will see if the substitution was not able to be fully done while retaining the original variables:

    >>> f = (x + y)**2 + 1/(4*x + 4*y + sin(2*x + 2*y))
    >>> (f+x).subs(x,z-y).subs(y,z-x)
    x + z**2 + 1/(4*z + sin(2*z))