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.
CodePudding user response:
from sympy import *
# unkowns
i1, i2, u1, u2 = symbols("i1, i2, u1, u2")
# knows quantities
id2, zg, zl, A, B, C, D, Y = symbols("id_2, z_g, z_l, A, B, C, D, Y")
# define equations:
# one way to do that is to write them as:
# (Left Hand Side) - (Right Hand Side) = 0
eq1 = i1 - (id2 - u1/zg)
eq2 = i2 - ((C D*Y)*u1 D* i1)
eq3 = i2 - (u2/zl)
eq4 = u2 - ((A B*Y)*u1 B*i1)
# solve the system of equation
sol = solve([eq1, eq2, eq3, eq4], [i1, i2, u1, u2])
# retrieve the solution of u2
sol[u2]
# out: (A*D*id_2*z_g*z_l - B*C*id_2*z_g*z_l)/(A*z_g B*Y*z_g - B - C*z_g*z_l - D*Y*z_g*z_l D*z_l)
CodePudding user response:
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.
CodePudding user response:
Did you know that this is one of the most asked questions? It often happens that somebody wants to solve with Python a Mathematics problem.
Mathematics is about num
bers, and one of the most used Python libraries is NumPy
, which has a function called linalg.solve
which does it for you.