如何用python编程求解二元一次方程组。如x+y=3;x-y=1

2025-03-07 16:27:52
推荐回答(2个)
回答1:

利用 numpy 很简单。可以利用pip安装

pip install numpy

然后(以你的方程为例),python 下

Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> a = np.array([[1,1],[1,-1]])
>>> b = np.array([3,1])
>>> print np.linalg.solve(a,b)
[ 2.  1.]

如果你学过 线性代数,那么这段代码很好理解。

回答2:

import sympy as sp
x = sp.Symbol('x')
y = sp.Symbol('y')
print(sp.solve([ 5*x + 1 - y, 1 - x-3*y],[x,y]))