C++使用雅可比迭代法(jacobi)和高斯赛德尔迭代法(G-S)解线性方程组

理论部分:

简言之

  • jacobi迭代法就是把线性方程组化为关于第i行xi的等式,然后利用等式循环计算xi
  • Gauss-Seidel迭代法就是在jacobi迭代的基础上,在计算第i+1行的xi+1时,带入了刚刚计算出的xi,xi-1…,以减少迭代次数
  • 迭代法不是万能的,收敛时才能用

迭代法的相关推导
迭代法的收敛性与谱半径

C++代码

C++使用雅可比迭代法(jacobi)和高斯赛德尔迭代法(G-S)解线性方程组_第1张图片

雅可比迭代法:

#include
#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] << " ";
	}
}

C++使用雅可比迭代法(jacobi)和高斯赛德尔迭代法(G-S)解线性方程组_第2张图片

高斯赛德尔迭代法:

#include
#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] << " ";
	}
}

C++使用雅可比迭代法(jacobi)和高斯赛德尔迭代法(G-S)解线性方程组_第3张图片

输入条件调教版本

你可能感兴趣的:(算法,数据结构和算法,C++排雷,c++,算法,开发语言)