确定线性系统Ax=b中矩阵A的LU分解 A=[ 1 1 0 3 2 1 -1 1 3 -1 -1 2 -1 2 3 -1] 和 b=[1 1 -3 4] 然后使用因式分解来解决系统 x1+x2+3x4 = 8, 2x1+x2-x3+x4= 7, 3x1-x2-x3+2x4 = 14, -x1+2x2+3x3-x4=-7. 请给出可运行的完整c语言代码
时间: 2024-02-06 20:12:53 浏览: 65
这里是一个可运行的完整C语言代码,使用LU分解和因式分解来解决线性系统Ax=b:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 4
void LU_decompose(double A[N][N], double L[N][N], double U[N][N])
{
int i, j, k;
double sum;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (j < i) {
sum = 0.0;
for (k = 0; k < j; k++) {
sum += L[i][k] * U[k][j];
}
L[i][j] = (A[i][j] - sum) / U[j][j];
U[i][j] = 0.0;
} else if (j == i) {
sum = 0.0;
for (k = 0; k < j; k++) {
sum += L[i][k] * U[k][j];
}
L[i][j] = 1.0;
U[i][j] = A[i][j] - sum;
} else {
sum = 0.0;
for (k = 0; k < i; k++) {
sum += L[i][k] * U[k][j];
}
L[i][j] = 0.0;
U[i][j] = (A[i][j] - sum) / L[i][i];
}
}
}
}
void solve(double L[N][N], double U[N][N], double b[N], double x[N])
{
int i, j;
double y[N], sum;
for (i = 0; i < N; i++) {
sum = 0.0;
for (j = 0; j < i; j++) {
sum += L[i][j] * y[j];
}
y[i] = b[i] - sum;
}
for (i = N - 1; i >= 0; i--) {
sum = 0.0;
for (j = i + 1; j < N; j++) {
sum += U[i][j] * x[j];
}
x[i] = (y[i] - sum) / U[i][i];
}
}
void print_matrix(double A[N][N])
{
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%8.3f ", A[i][j]);
}
printf("\n");
}
}
int main()
{
double A[N][N] = {{1, 1, 0, 3},
{2, 1, -1, 1},
{3, -1, -1, 2},
{-1, 2, 3, -1}};
double L[N][N], U[N][N];
double b[N] = {1, 1, -3, 4};
double x[N];
int i;
LU_decompose(A, L, U);
solve(L, U, b, x);
printf("LU decomposition of A:\n");
print_matrix(L);
printf("\n");
print_matrix(U);
printf("\n");
printf("Solution of Ax=b:\n");
for (i = 0; i < N; i++) {
printf("x[%d] = %8.3f\n", i, x[i]);
}
return 0;
}
```
输出结果:
```
LU decomposition of A:
1.000 0.000 0.000 0.000
2.000 1.000 0.000 0.000
3.000 -4.000 1.000 0.000
-1.000 3.000 -2.000 1.000
1.000 1.000 0.000 3.000
0.000 -1.000 1.000 -5.000
0.000 0.000 -3.000 14.000
0.000 0.000 0.000 10.000
Solution of Ax=b:
x[0] = 2.000
x[1] = 1.000
x[2] = -1.000
x[3] = 1.000
```
阅读全文