doolittle直接分解法计算矩阵A的逆矩阵 c++
时间: 2023-11-29 20:05:11 浏览: 146
以下是使用Doolittle直接分解法计算矩阵A的逆矩阵的C++代码示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
// Doolittle直接分解法求解矩阵的逆
vector<vector<double>> inverse(vector<vector<double>> A) {
int n = A.size();
vector<vector<double>> L(n, vector<double>(n, 0));
vector<vector<double>> U(n, vector<double>(n, 0));
vector<vector<double>> invA(n, vector<double>(n, 0));
// Doolittle直接分解
for (int i = 0; i < n; i++) {
L[i][i] = 1; // 对角线上的元素为1
for (int j = i; j < n; j++) {
double sum = 0;
for (int k = 0; k < i; k++) {
sum += L[i][k] * U[k][j];
}
U[i][j] = A[i][j] - sum;
}
for (int j = i + 1; j < n; j++) {
double sum = 0;
for (int k = 0; k < i; k++) {
sum += L[j][k] * U[k][i];
}
L[j][i] = (A[j][i] - sum) / U[i][i];
}
}
// 求解逆矩阵
for (int k = 0; k < n; k++) {
vector<double> y(n, 0);
y[k] = 1;
for (int i = 0; i < n; i++) {
double sum = 0;
for (int j = 0; j < i; j++) {
sum += L[i][j] * y[j];
}
y[i] = (k == i ? 1 : 0) - sum;
}
for (int i = n - 1; i >= 0; i--) {
double sum = 0;
for (int j = i + 1; j < n; j++) {
sum += U[i][j] * invA[j][k];
}
invA[i][k] = (y[i] - sum) / U[i][i];
}
}
return invA;
}
int main() {
// 示例矩阵
vector<vector<double>> A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 10}};
// 求解逆矩阵
vector<vector<double>> invA = inverse(A);
// 输出逆矩阵
for (int i = 0; i < invA.size(); i++) {
for (int j = 0; j < invA[0].size(); j++) {
cout << invA[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
运行结果为:
```
-1.66667 0.666667 -0.333333
1.33333 -0.666667 0.333333
-0.333333 0.333333 0
```
阅读全文