高斯赛德尔迭代法大家可以从网站上找到相关的公式推导,这里给出它的C++算法实现和运行的结果。
#include<iostream>
#include<math.h>
using namespace std;
int n; //定义全局变量
double a[100][100], b[100], x[100][100];
double e;
void input_func()
{
for (int i = 0;i < n;i++)
{
for (int j = 0;j < n;j++) //输入系数矩阵
cin >> a[i][j]; //输入等式右边的矩阵
cin >> b[i];
}
}
void cal_func() { //定义Gauss-Seidel迭代函数
for (int k = 1;k <= 10;k++)
{
for (int i = 0;i < n;i++)
{
double s1 = 0, s2 = 0, s = 0;
x[k][i] = 1.0 / a[i][i];
double re = b[i]; //每一行遍历完re重置
for (int j = 0;j < n;j++)
{
if (i < j) //上三角部分乘系数求和
s1 += a[i][j] * x[k - 1][j];
else if(i > j) //下三角部分乘系数求和
s2 += a[i][j] * x[k][j];
}
s = s1 + s2; //每一行遍历完求和
re -= s;
x[k][i] *= re;
}
for (int i = 0;i < n;i++)
cout << x[k][i] << " ";cout << endl; //输出第k遍迭代的X0、X1、X2
bool judge = true;
for (int i = 0;i < n;i++)
if (fabs(x[k - 1][i] - x[k][i]) > e) {
judge = false;break;
}
if (judge == true) return;
}
}
int main()
{
cout << "系数输入矩阵的阶数" << endl;
cin >> n;
cout << "请输入系数矩阵" << endl;
input_func();
cout << "请输入初始向量" << endl;
for (int i = 0;i < n;i++) cin >> x[0][i];
cout << "输入求得的精度" << endl;
cin >> e;
cal_func();
return 0;
}