利用赛德尔迭代法求解如下线性代数方程组的近似解系数矩阵a[3][3]={{10,-1,-2},{-1,10,-2},{-1,-2,5}},b[3]={7.2,8.3,4.2},写出迭代次数k和解的C语言和c++代码(误差控制限为5e-5,迭代初始值取[0,0,0])
时间: 2023-08-19 21:14:00 浏览: 177
迭代公式为:$x^{(k+1)}=D^{-1}(b-(L+U)x^{(k)})$,其中D为系数矩阵的对角线部分,L为系数矩阵的下三角部分,U为系数矩阵的上三角部分。
C语言代码如下:
```c
#include <stdio.h>
#include <math.h>
#define N 3
#define MAX_ITER 1000
#define TOLERANCE 5e-5
void print_solution(double x[N]) {
printf("Solution: ");
for (int i = 0; i < N; i++) {
printf("%lf ", x[i]);
}
printf("\n");
}
int main() {
double a[N][N] = {{10, -1, -2}, {-1, 10, -2}, {-1, -2, 5}};
double b[N] = {7.2, 8.3, 4.2};
double x[N] = {0, 0, 0};
double x_new[N];
double D[N], L[N][N], U[N][N];
// 分解系数矩阵
for (int i = 0; i < N; i++) {
D[i] = a[i][i];
for (int j = 0; j < N; j++) {
if (i < j) {
U[i][j] = a[i][j];
} else if (i > j) {
L[i][j] = a[i][j];
}
}
}
// 判断对角线元素是否为0,如果是则无解
for (int i = 0; i < N; i++) {
if (D[i] == 0) {
printf("No solution\n");
return 0;
}
}
// 迭代求解
int k;
for (k = 0; k < MAX_ITER; k++) {
for (int i = 0; i < N; i++) {
x_new[i] = b[i];
for (int j = 0; j < N; j++) {
x_new[i] -= (L[i][j] + U[i][j]) * x[j];
}
x_new[i] /= D[i];
}
// 判断误差是否满足要求
double error = 0;
for (int i = 0; i < N; i++) {
error += pow(x_new[i] - x[i], 2);
}
if (sqrt(error) < TOLERANCE) {
break;
}
// 更新迭代值
for (int i = 0; i < N; i++) {
x[i] = x_new[i];
}
}
if (k == MAX_ITER) {
printf("Iteration failed\n");
} else {
printf("Iteration succeeded in %d steps\n", k);
print_solution(x_new);
}
return 0;
}
```
C++代码如下:
```cpp
#include <iostream>
#include <cmath>
#define N 3
#define MAX_ITER 1000
#define TOLERANCE 5e-5
using namespace std;
void print_solution(double x[N]) {
cout << "Solution: ";
for (int i = 0; i < N; i++) {
cout << x[i] << " ";
}
cout << endl;
}
int main() {
double a[N][N] = {{10, -1, -2}, {-1, 10, -2}, {-1, -2, 5}};
double b[N] = {7.2, 8.3, 4.2};
double x[N] = {0, 0, 0};
double x_new[N];
double D[N], L[N][N], U[N][N];
// 分解系数矩阵
for (int i = 0; i < N; i++) {
D[i] = a[i][i];
for (int j = 0; j < N; j++) {
if (i < j) {
U[i][j] = a[i][j];
} else if (i > j) {
L[i][j] = a[i][j];
}
}
}
// 判断对角线元素是否为0,如果是则无解
for (int i = 0; i < N; i++) {
if (D[i] == 0) {
cout << "No solution" << endl;
return 0;
}
}
// 迭代求解
int k;
for (k = 0; k < MAX_ITER; k++) {
for (int i = 0; i < N; i++) {
x_new[i] = b[i];
for (int j = 0; j < N; j++) {
x_new[i] -= (L[i][j] + U[i][j]) * x[j];
}
x_new[i] /= D[i];
}
// 判断误差是否满足要求
double error = 0;
for (int i = 0; i < N; i++) {
error += pow(x_new[i] - x[i], 2);
}
if (sqrt(error) < TOLERANCE) {
break;
}
// 更新迭代值
for (int i = 0; i < N; i++) {
x[i] = x_new[i];
}
}
if (k == MAX_ITER) {
cout << "Iteration failed" << endl;
} else {
cout << "Iteration succeeded in " << k << " steps" << endl;
print_solution(x_new);
}
return 0;
}
```
阅读全文