doolittle直接分解法求线性方程组Ax=b c++
时间: 2024-02-23 17:02:23 浏览: 152
用LU分解法求解n阶线性代数方程AX=b c++实现
4星 · 用户满意度95%
Doolittle分解是一种LU分解的方法,用于求解线性方程组Ax=b。下面是使用C++实现Doolittle分解的代码:
```
#include <iostream>
using namespace std;
const int N = 100;
double A[N][N], L[N][N], U[N][N];
double b[N], x[N], y[N];
void doolittle(int n)
{
// Doolittle分解
for (int k = 0; k < n; k++) {
U[k][k] = A[k][k];
for (int i = k; i < n; i++) {
L[i][k] = A[i][k] / U[k][k];
U[k][i] = A[k][i];
}
for (int i = k + 1; i < n; i++) {
for (int j = k + 1; j < n; j++) {
A[i][j] -= L[i][k] * U[k][j];
}
}
}
}
void solve(int n)
{
// 前代
y[0] = b[0] / L[0][0];
for (int i = 1; i < n; i++) {
double sum = 0;
for (int j = 0; j < i; j++) {
sum += L[i][j] * y[j];
}
y[i] = (b[i] - sum) / L[i][i];
}
// 后代
x[n - 1] = y[n - 1] / U[n - 1][n - 1];
for (int i = n - 2; i >= 0; i--) {
double sum = 0;
for (int j = i + 1; j < n; j++) {
sum += U[i][j] * x[j];
}
x[i] = (y[i] - sum) / U[i][i];
}
}
int main()
{
int n;
cout << "请输入线性方程组的阶数:";
cin >> n;
cout << "请输入系数矩阵A:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> A[i][j];
}
}
cout << "请输入常数向量b:" << endl;
for (int i = 0; i < n; i++) {
cin >> b[i];
}
doolittle(n); // Doolittle分解
solve(n); // 求解方程组
cout << "方程组的解为:" << endl;
for (int i = 0; i < n; i++) {
cout << "x" << i + 1 << " = " << x[i] << endl;
}
return 0;
}
```
注意:该算法中的矩阵下标从0开始。
阅读全文