Theoretical part:
in short
- The jacobi iterative method is to transform the linear equation into an equation about the i-th row xi, and then use the equation to calculate xi
- The Gauss-Seidel iteration method is based on the jacobi iteration, when calculating xi+1 in the i+1th row, it brings in the just calculated xi,xi-1... to reduce the number of iterations
- The iterative method is not a panacea, it can only be used when it converges
Correlation Derivation of Iterative Method
Convergence and Spectral Radius of Iterative Method
C++ code
Jacobian iteration method:
#include<bits/stdc++.h>
#define MAXSIZE 100
using namespace std;
int main() {
double A[MAXSIZE][MAXSIZE], x[MAXSIZE], b[MAXSIZE],re[MAXSIZE];
int n;
double e;
cout << " 请输入原方程的阶数:";
cin >> n;
cout << "请输入原方程的增广矩阵:";
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n ; ++j) {
cin >> A[i][j];
}
cin >> b[i];
}
cout << "请输入初始迭代向量值";
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
cout << "请输入误差上限";
cin >> e;
int count = 0;
while (true) {
cout << "第" << ++count << "次迭代:";
int flag = 0;
for (int i = 0; i < n; ++i) {
re[i] = 0;
for (int j = 0; j < n; ++j) {
if (i != j) {
re[i] += - A[i][j] * x[j];
}
}
re[i] = (re[i] + b[i]) / A[i][i];
if (fabs(x[i] - re[i]) < e)
++flag;
cout << re[i]<<" ";
}
cout << endl;
if (flag == n) break;
for (int i = 0; i < n; ++i) {
x[i] = re[i];
}
}
for (int i = 0; i < n; ++i) {
cout << re[i] << " ";
}
}
Gauss-Seidel iteration method:
#include<bits/stdc++.h>
#define MAXSIZE 100
using namespace std;
int main() {
double A[MAXSIZE][MAXSIZE], x[MAXSIZE], b[MAXSIZE];
int n;
double e;
cout << " 请输入原方程的阶数:";
cin >> n;
cout << "请输入原方程的增广矩阵:";
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n ; ++j) {
cin >> A[i][j];
}
cin >> b[i];
}
cout << "请输入初始迭代向量值";
for (int i = 0; i < n; ++i) {
cin >> x[i];
}
cout << "请输入误差上限";
cin >> e;
int count = 0;
while (true) {
cout << "第" << ++count << "次迭代:";
int flag = 0;
for (int i = 0; i < n; ++i) {
double tmp = x[i];
x[i] = 0;
for (int j = 0; j < n; ++j) {
if (i != j) {
x[i] += - A[i][j] * x[j];
}
}
x[i] = (x[i] + b[i]) / A[i][i];
if (fabs(x[i] - tmp) < e)
++flag;
cout << x[i]<<" ";
}
cout << endl;
if (flag == n) break;
}
for (int i = 0; i < n; ++i) {
cout << x[i] << " ";
}
}