如何在SymPy中求解线性方程组?

问题描述 投票:15回答:5

对不起,我对sympy和python很新。

我想解决以下欠定线性方程组:

x + y + z = 1 
x + y + 2z = 3
python math sympy
5个回答
25
投票

SymPy最近得到了一个新的线性系统求解器:linsolve中的sympy.solvers.solveset,你可以使用如下:

In [38]: from sympy import *

In [39]: from sympy.solvers.solveset import linsolve

In [40]: x, y, z = symbols('x, y, z')

方程列表形式:

In [41]: linsolve([x + y + z - 1, x + y + 2*z - 3 ], (x, y, z))
Out[41]: {(-y - 1, y, 2)}

增强矩阵形式:

In [59]: linsolve(Matrix(([1, 1, 1, 1], [1, 1, 2, 3])), (x, y, z))
Out[59]: {(-y - 1, y, 2)}

A * x = b表格

In [59]: M = Matrix(((1, 1, 1, 1), (1, 1, 2, 3)))

In [60]: system = A, b = M[:, :-1], M[:, -1]

In [61]: linsolve(system, x, y, z)
Out[61]: {(-y - 1, y, 2)}

注意:解决方案顺序对应给定符号的顺序。


9
投票

除了@AMiT Kumar和@Scott给出的出色答案外,SymPy 1.0还增加了更多功能。对于欠定的线性方程组,我在下面尝试并使其工作而不深入sympy.solvers.solveset。话虽这么说,如果好奇心引导你,那就去那里吧。

from sympy import *
x, y, z = symbols('x, y, z')
eq1 = x + y + z
eq2 = x + y + 2*z
solve([eq1-1, eq2-3], (x, y,z))

这给了我{z: 2, x: -y - 1}。再次,伟大的包,SymPy开发人员!


2
投票

你可以用矩阵形式Ax=b解决(在这种情况下是一个未确定的系统,但我们可以使用solve_linear_system):

from sympy import Matrix, solve_linear_system

x, y, z = symbols('x, y, z')
A = Matrix(( (1, 1, 1, 1), (1, 1, 2, 3) ))
solve_linear_system(A, x, y, z)

{x: -y - 1, z: 2}

或重写为(我的编辑,而不是同情):

[x]=  [-1]   [-1]
[y]= y[1]  + [0]
[z]=  [0]    [2]

在正方形A的情况下,我们可以定义b并使用A.LUsolve(b)


2
投票

关于矩阵线性系统方程的另一个例子,假设我们正在为这个系统求解:

enter image description here

SymPy,我们可以做类似的事情:

>>> import sympy as sy
... sy.init_printing()

>>> a, b, c, d = sy.symbols('a b c d')
... A = sy.Matrix([[a-b, b+c],[3*d + c, 2*a - 4*d]])
... A

⎡ a - b     b + c  ⎤
⎢                  ⎥
⎣c + 3⋅d  2⋅a - 4⋅d⎦


>>> B = sy.Matrix([[8, 1],[7, 6]])
... B

⎡8  1⎤
⎢    ⎥
⎣7  6⎦


>>> A - B

⎡ a - b - 8     b + c - 1  ⎤
⎢                          ⎥
⎣c + 3⋅d - 7  2⋅a - 4⋅d - 6⎦


>>> sy.solve(A - B, (a, b, c, d))
{a: 5, b: -3, c: 4, d: 1}

1
投票
import sympy as sp
x, y, z = sp.symbols('x, y, z')
eq1 = sp.Eq(x + y + z, 1)             # x + y + z  = 1
eq2 = sp.Eq(x + y + 2 * z, 3)         # x + y + 2z = 3
ans = sp.solve((eq1, eq2), (x, y, z))

这类似于@PaulDong的回答,有一些细微的变化

  1. 习惯不使用import *的好习惯(numpy有许多类似的功能)
  2. 使用sp.Eq()定义方程式会在以后产生更清晰的代码
© www.soinside.com 2019 - 2024. All rights reserved.