我从MATLAB到Python新手。我现在在Python中解决方程系统的问题。例如,在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是系数y1 y10是我需要解决的问题,它们应该是解决后的符号表达式。如何在Python中执行此操作?
答案 0 :(得分:1)
NumPy没有符号解决方案的概念。您可以按如下方式使用SymPy:
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])
输出为{(y1/3, 0, 0, 0, 0, y6/5, y1, 0, 0, 0, 0, y6)}
,表示大多数变量必须为0,x1必须为y1 / 3,x5必须为y6 / 6,变量y1,y2可以为whataver。
以上使用linsolve
,因为系统在每个未知数中都是线性的。其他solvers可用于非线性方程。
请注意,公式可以输入为lhs - rhs
(如上所述)或Eq(lhs, rhs)
。不像lhs == rhs
那样会在Python中立即评估为False。