How do I use SymPy to simplify by substitution a number of equations to get to a single simplified equation?

72 Views Asked by At

My question is exactly like the title of my post. Attached is an image with an example of what I would like to achieve.

Description of problem I have updated this file after the original post and after the problem was solved to correct a typo.

Note Vref in the picture of the description is zero.

The attempts to get the SymPy functions mentioned to work failed.

1

There are 1 best solutions below

2
Davide_sd On

Finding the solution you are looking for is really easy. First, you find Vx from eq1, substitutes it into eq2 and solve it for Vo:

from sympy import *
Vi, Vo, Vx = symbols("Vi, Vo, Vx")
R1, R2, R3, R4 = symbols("R1:5")

eq1 = Eq((0 - Vi) / R1, (Vi - Vx) / R2)
eq2 = Eq((Vi - Vx) / R2, Vx / R4 + (Vx - Vo) / R3)
Vx_expr = solve(eq1, Vx)[0]
Vo_expr = solve(eq2.subs(Vx, Vx_expr), Vo)[0]
Vo_expr

enter image description here

Now, if you want to transform it into the output you see on your screenshot, you have to use expression manipulation, which is pure masochism for a SymPy's novice. I'll show you how I'd do it.

In the following, you'll see several sympy's function in action. It is your job to read their documentation.

Vo_expr = Vo_expr.expand().collect(Vi)
Vo_expr

enter image description here

Now, I want to see the order of the arguments of the big addition:

Vo_expr.args[1].args

enter image description here

I select the terms that I need to modify:

term1 = Add(*[t for i, t in enumerate(Vo_expr.args[1].args) if i in [3, 4]])
display(term1, term1.together())

enter image description here

term2 = Add(*[t for i, t in enumerate(Vo_expr.args[1].args) if i in [1, 2]])
display(term2, term2.together())

enter image description here

Then, I substitute the terms with their modified forms:

Vo_final = Vo_expr.subs({term1: term1.together(), term2: term2.together()})
Vo_final

enter image description here

Finally, I verify that the result is equal to the original expression:

Vo_final.equals(Vo_expr)
# out: True