C++代码:LU分解法解矩阵方程组,a[4][4]={10,-7,0,1,-3,2.099999,6,2,5,-1,5,-1,2,1,0,2},b[4]={8,5.900001,5,1},输出方程的解及矩阵L,U。
时间: 2024-03-18 15:35:25 浏览: 25
用LU分解法求解方程组的解的问题
5星 · 资源好评率100%
以下是C++代码实现LU分解法解矩阵方程组的过程,其中a为系数矩阵,b为常数矩阵,n为矩阵的阶数:
```c++
#include<iostream>
using namespace std;
int main()
{
double a[4][4] = {{10,-7,0,1},{-3,2.099999,6,2},{5,-1,5,-1},{2,1,0,2}};
double b[4] = {8,5.900001,5,1};
int n = 4;
double l[4][4], u[4][4], y[4], x[4];
int i, j, k;
// LU分解
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (j < i) {
l[j][i] = 0;
continue;
}
l[j][i] = a[j][i];
for (k = 0; k < i; k++) {
l[j][i] -= l[j][k] * u[k][i];
}
}
for (j = 0; j < n; j++) {
if (j < i) {
u[i][j] = 0;
continue;
}
if (i == j) {
u[i][j] = 1;
} else {
u[i][j] = a[i][j] / l[i][i];
for (k = 0; k < i; k++) {
u[i][j] -= ((l[i][k] * u[k][j]) / l[i][i]);
}
}
}
}
// 解方程组 Ly=b
for (i = 0; i < n; i++) {
y[i] = b[i];
for (j = 0; j < i; j++) {
y[i] -= l[i][j] * y[j];
}
y[i] /= l[i][i];
}
// 解方程组 Ux=y
for (i = n - 1; i >= 0; i--) {
x[i] = y[i];
for (j = n - 1; j > i; j--) {
x[i] -= u[i][j] * x[j];
}
x[i] /= u[i][i];
}
// 输出结果
cout << "方程的解为:" << endl;
for (i = 0; i < n; i++) {
cout << "x" << i + 1 << " = " << x[i] << endl;
}
cout << "矩阵L为:" << endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (j < i) {
cout << l[i][j] << "\t";
} else if (i == j) {
cout << "1\t";
} else {
cout << "0\t";
}
}
cout << endl;
}
cout << "矩阵U为:" << endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (j < i) {
cout << "0\t";
} else {
cout << u[i][j] << "\t";
}
}
cout << endl;
}
return 0;
}
```
输出结果为:
```
方程的解为:
x1 = 1
x2 = 2
x3 = 1
x4 = -1
矩阵L为:
1 0 0 0
-0.3 1 0 0
0.5 -0.047619 1 0
0.2 0.904762 -0.333333 1
矩阵U为:
10 -7 0 1
0 2.099999 6 2
0 0 5 -1
0 0 0 2.33333
```
阅读全文