sun0727
sun0727

Reputation: 394

How to solve symbolic equation system in Python?

I am new from MATLAB to Python. I have now problem with solve equation system in Python. For example, in Matlab

R = solve( a1*[x1; x2] == [y1;y2], ...  
           a2*[x3; x4] == [y3;y4], ...
           a3*[x5; x6] == [y5;y6], ... 
           x2 == y3, x3 == y2, ...        
           x4 == y5, x5 == y4, ... 
           [    x2 x3 x4 x5    ...   
             y1 y2 y3 y4 y5 y6]...   % unknown
          );
y1 = simplify(R.y1);
y10 = simplify(R.y10);

a1..a5 are coefficient y1 y10 are what I need to solve and they should be symbolic expression after solve. How to do this in Python?

Upvotes: 2

Views: 10430

Answers (1)

user6655984
user6655984

Reputation:

NumPy has no concept of symbolic solutions. You can use SymPy as follows:

from sympy import *
a1, a2, a3 = 3, 4, 5   #   known coefficients, they could be symbols too
x1, x2, x3, x4, x5, x6 = symbols('x1:7')
y1, y2, y3, y4, y5, y6 = symbols('y1:7')
eqns = [a1*x1 - y1, a1*x2 - y2, a2*x3 - y3, a2*x4 - y4, a3*x5 - y5, a3*x6 - y6, 
        x2 - y3, x3 - y2, x4 - y5, x5 - y4]
linsolve(eqns, [x1, x2, x3, x4, x5, x6, y1, y2, y3, y4, y5, y6])

The output is {(y1/3, 0, 0, 0, 0, y6/5, y1, 0, 0, 0, 0, y6)} indicating that most of variables must be 0, x1 must be y1/3, x5 must be y6/6, and the variables y1, y2 can be whataver.

The above uses linsolve because the system is linear in each of the unknowns. Other solvers are available for nonlinear equations.

Note that equations can be entered as either lhs - rhs (as I did above) or Eq(lhs, rhs). Not as lhs == rhs which would immediately evaluate to False in Python.

Upvotes: 6

Related Questions