Sympy's subs limitations
<p>I am working with some long equations but not really complex, and I wanted to use <strong>sympy</strong> to simplify and "factorize" them. But I have encountered a few problems. Here is a list of some minimal examples:</p>

<p><strong>Problem 1: symmetry</strong></p>

<pre><code>from sympy import *
from __future__ import division
a = symbols('a')
b = symbols('b')
expr = 1/12*b + 1
expr.subs(1/12*b, a)
expr.subs(b*1/12, a)
</code></pre>

<p>The first line gives the expected result (ie. <code>a+1</code>) while in the second one there is no substitution.</p>

<p><strong>Problem 2: factorized expressions</strong></p>

<p>Some parts of the expression are factorized and when I expand the expression they get simplified, thus making the substitution impossible. For example</p>

<pre><code>(((x+1)**2-x).expand()).subs(x**2+2*x, y+1)
</code></pre>

<p>will give <code>x^2+x+1</code> and what I am looking for is <code>y+2-x</code>.</p>

<p><strong>Question</strong></p>

<p>Is there a way to solve these problems ? Or maybe I should use another symbolic mathematical tool ? Any suggestions are welcomed.</p>

<p>Regarding problem 1, note that <code>1/12*b</code> and <code>b*1/12</code> are <em>not</em> the same thing in sympy. The first is a floating number mutliplied by a symbol, whereas the second is an exact symbolic expression (you can check it out by a simple print statement). Since <code>expr</code> contains <code>1/12*b</code>, it is not surprising that the second <code>subs</code> does not work. </p>

<p>Regarding problem 2, the <code>subs</code> rule you provide is ambiguous. In particular the substitution rule implies that equation <code>x**2+2*x==y+1</code>. However, this equation has many interpretations, e.g, </p>

<p><code>x**2 == y + 1 - 2*x</code> (this is the one you consider),</p>

<p><code>x**2 + x == y + 1 - x</code>, </p>

<p><code>x == (y + 1 - x**2)/2</code>,</p>

<p>For this reason, I consider sympy refusing to perform a substitution is actually a correct approach.</p>

<p>If it is the first interpretation you want, it is better to explicitly provide it in the <code>subs</code> rule, i.e., </p>

<pre><code>(((x+1)**2-x).expand()).subs(x**2, -2*x + y + 1)
</code></pre>

<blockquote>
  <p><code>-x + y + 2</code></p>
</blockquote>

python sympy substitution symbolic-math