'Solve system of linear equations in Python

I have a system of symbolic linear equations

i1 = id2 - u1/zg
i2 = (C+D*Y)*u1 + D* i1
i2 = u2/zl
u2 = (A+B*Y)*u1 + B*i1

My goal is the solution for u2, where u1 and i1 are substituted with their corresponding solutions declared above. The solution for u2 is this huge equation, calculated by hand for now

u2 = (A+B*Y)*(id1*zg*(-B + D*zl)/(A*zg + B*Y*zg - B - C*zg*zl - D*Y*zg*zl + D*zl)) + B * (id1 - (id1*zg*(-B + D*zl)/(A*zg + B*Y*zg - B - C*zg*zl - D*Y*zg*zl + D*zl))/zg) 

Im sure theres a way to let Python calculate this for me, because it takes ages and is very error prone doing this manually.

Basically I want that Python eliminates all unknown variables (except one, which I then can calculate) for me. In the example set of equations above, i1 i2 u1 and u2 are unknown. Everything else is known.

Thanks for your help.



Solution 1:[1]

Alright, I solved it as follows:

equations = [
    sym.Eq( (C+D*Y)*u1 + D* i1 , i2 ),
    sym.Eq( id2 - u1/zg, i1),
    sym.Eq(u2/zl, i2),
    sym.Eq( (A+B*Y)*u1 + B*i1, u2 )
]

eq = sym.solve(equations, u2)

I tried exactly that before, but must had a typo somewhere.

The result is

id1*zg*(-B + D*zl)/(A*zg + B*Y*zg - B - C*zg*zl - D*Y*zg*zl + D*zl)

Its way shorter than the result i calculated per hand, but it seems to be correct.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 aberr