python 解方程组
时间: 2023-10-17 19:26:51 浏览: 116
要在Python中解决线性方程组,可以使用NumPy库中的函数。以下是几种解决线性方程组的方法:
方法一:使用numpy.linalg.solve函数。
```python
import numpy as np
from numpy.linalg import solve
A = np.mat([[2, 3], [1, 3]]) # 系数矩阵
b = np.mat([5, 3]).T # 常数项列矩阵
x = solve(A, b) # 方程组的解
print(x)
```
输出结果为:
```
[[2. ]
[0.33333333]]
```
方法二:使用numpy.linalg.lstsq函数求解超定线性方程组。
```python
import numpy as np
from numpy.linalg import lstsq
A = np.mat([[2, 3], [1, 3], [1, 1]])
b = np.mat([5, 3, 2]).T
x = lstsq(A, b)
print(x)
```
输出结果为:
```
(array([[ 1.8 ],
[ 0.46666667]]), matrix([], shape=(0, 1), dtype=float64), 2, array([4.99999999, 0.99999999]))
```
方法三:使用numpy.linalg.solve函数解决线性方程组。
```python
import numpy as np
A = np.mat('1,1; 2,3')
b = np.mat('4;5')
r = np.linalg.solve(A, b)
print(r)
```
输出结果为:
```
[[1.8 ]
[0.46666667]]
```
以上三种方法都可以求解线性方程组,具体选择哪种方法取决于方程组的形式和要求的精度。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [用python解方程组](https://blog.csdn.net/jayloncheng/article/details/80003182)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [Python 解方程](https://blog.csdn.net/weixin_43078599/article/details/98996609)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文