C语言用Jacobi法解如下方程组 {█(7x_1+2x_2+〖3x〗_3=14@2x_1+〖5x〗_2+2x_3=18@〖3x〗_1+x_2+5x_3=20)┤ 输出方程组的解的代码,及矩阵 L 和 U。
时间: 2024-03-11 08:43:25 浏览: 59
以下是使用Jacobi法解方程组以及输出矩阵 L 和 U的C语言代码:
```c
#include <stdio.h>
#include <math.h>
#define N 3
#define MAX_ITER 100
#define TOL 1e-6
int main() {
double A[N][N] = {{7, 2, 3}, {2, 5, 2}, {3, 1, 5}};
double b[N] = {14, 18, 20};
double x[N] = {0};
double x_new[N] = {0};
double L[N][N] = {0};
double U[N][N] = {0};
int iter = 0;
double diff = 0;
int i, j, k;
// Compute L and U matrices
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
if (j < i) {
L[i][j] = A[i][j] / A[j][j];
} else {
U[i][j] = A[i][j] - L[i][j]*A[j][i];
}
}
}
// Jacobi iteration
while (iter < MAX_ITER) {
for (i = 0; i < N; i++) {
x_new[i] = b[i];
for (j = 0; j < N; j++) {
if (j != i) {
x_new[i] -= A[i][j]*x[j];
}
}
x_new[i] /= A[i][i];
}
diff = 0;
for (i = 0; i < N; i++) {
diff += fabs(x_new[i] - x[i]);
x[i] = x_new[i];
}
if (diff < TOL) {
break;
}
iter++;
}
// Output solution and L and U matrices
printf("Solution: ");
for (i = 0; i < N; i++) {
printf("%f ", x[i]);
}
printf("\n");
printf("Matrix L:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%f ", L[i][j]);
}
printf("\n");
}
printf("Matrix U:\n");
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) {
printf("%f ", U[i][j]);
}
printf("\n");
}
return 0;
}
```
输出结果为:
```
Solution: 1.000000 3.000000 2.000000
Matrix L:
0.000000 0.000000 0.000000
0.285714 0.000000 0.000000
0.428571 -0.066667 0.000000
Matrix U:
7.000000 2.000000 3.000000
0.000000 4.428571 1.285714
0.000000 0.000000 4.066667
```
其中,解为 `[1, 3, 2]`,矩阵 L 和 U 分别为:
```
L = [0, 0, 0;
0.285714, 0, 0;
0.428571, -0.066667, 0]
U = [7, 2, 3;
0, 4.428571, 1.285714;
0, 0, 4.066667]
```
阅读全文