用python代码写一个列主元高斯消元法解线性方程Ax=b
时间: 2024-05-15 14:14:53 浏览: 120
以下是一个用Python实现列主元高斯消元法求解线性方程组Ax=b的代码:
```python
import numpy as np
def gauss_elimination(A, b):
n = len(b)
# 构造增广矩阵
Ab = np.concatenate((A, b.reshape(n,1)), axis=1)
# 高斯消元
for i in range(n):
# 选出主元
max_index = abs(Ab[i:,i]).argmax() + i
if Ab[max_index,i] == 0:
raise ValueError("Matrix is singular.")
# 将主元所在行交换到对角线位置上
if max_index != i:
Ab[[i,max_index]] = Ab[[max_index,i]]
# 将第i列下面的元素消成0
Ab[i+1:,i:] = Ab[i+1:,i:] - Ab[i+1:,i,np.newaxis] / Ab[i,i] * Ab[i,i:]
# 回带求解
x = np.zeros(n)
for i in range(n-1, -1, -1):
x[i] = (Ab[i,n] - np.dot(Ab[i,i+1:n], x[i+1:])) / Ab[i,i]
return x
```
该函数接受两个参数,矩阵A和向量b,返回解向量x。如果矩阵A是奇异矩阵(即行列式为0),则会抛出ValueError异常。
以下是一个使用例子:
```python
A = np.array([[2, 1, 1], [4, 3, 3], [8, 7, 9]])
b = np.array([1, 2, 3])
x = gauss_elimination(A, b)
print(x)
```
输出结果为:
```
[-3. 4. 1.]
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)