Python – Factor/collect expression in Sympy


I have an equation like:

     R₂⋅V₁ + R₃⋅V₁ - R₃⋅V₂
i₁ = ─────────────────────
     R₁⋅R₂ + R₁⋅R₃ + R₂⋅R₃

defined and I'd like to split it into factors that include only single variable – in this case V1 and V2.

So as a result I'd expect

        -R₃                        (R₂ + R₃)
i₁ = V₂⋅───────────────────── + V₁⋅─────────────────────
        R₁⋅R₂ + R₁⋅R₃ + R₂⋅R₃      R₁⋅R₂ + R₁⋅R₃ + R₂⋅R₃

But the best I could get so far is

     -R₃⋅V₂ + V₁⋅(R₂ + R₃)
i₁ = ─────────────────────
     R₁⋅R₂ + R₁⋅R₃ + R₂⋅R₃

using equation.factor(V1,V2). Is there some other option to factor or another method to separate the variables even further?

Best Solution

If it was possible to exclude something from the factor algorithm (the denominator in this case) it would have been easy. I don't know a way to do this, so here is a manual solution:

In [1]: a

r₁⋅v₁ + r₂⋅v₂ + r₃⋅v₂
r₁⋅r₂ + r₁⋅r₃ + r₂⋅r₃

In [2]: b,c = factor(a,v2).as_numer_denom()

In [3]: b.args[0]/c + b.args[1]/c

        r₁⋅v₁                v₂⋅(r₂ + r₃)    
───────────────────── + ─────────────────────
r₁⋅r₂ + r₁⋅r₃ + r₂⋅r₃   r₁⋅r₂ + r₁⋅r₃ + r₂⋅r₃

You may also look at the evaluate=False options in Add and Mul, to build those expressions manually. I don't know of a nice general solution.

In[3] can be a list comprehension if you have many terms.

You may also check if it is possible to treat this as multivariate polynomial in v1 and v2. It may give a better solution.

Related Question