c++实现赛德尔迭代法求解方程组
时间: 2023-07-30 07:06:36 浏览: 117
下面是使用C++实现赛德尔迭代法求解n元线性方程组的代码:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
const int N = 3; //方程组未知数个数
int main()
{
double a[N][N] = {{4, -1, 0}, {-1, 4, -1}, {0, -1, 4}}; //系数矩阵
double b[N] = {7, 4, -7}; //常数列
double x[N] = {0}; //初始解向量
double x0[N] = {0}; //上一次的解向量
double eps = 1e-6; //精度要求
int k = 0; //迭代次数
do
{
k++;
for (int i = 0; i < N; i++)
{
double sum1 = 0, sum2 = 0;
for (int j = 0; j < i; j++)
{
sum1 += a[i][j] * x[j];
}
for (int j = i + 1; j < N; j++)
{
sum2 += a[i][j] * x0[j];
}
x[i] = (b[i] - sum1 - sum2) / a[i][i];
}
double delta = 0;
for (int i = 0; i < N; i++)
{
delta += (x[i] - x0[i]) * (x[i] - x0[i]);
x0[i] = x[i];
}
} while (sqrt(delta) > eps);
cout << "Solution:" << endl;
for (int i = 0; i < N; i++)
{
cout << "x[" << i << "] = " << x[i] << endl;
}
cout << "Iterations: " << k << endl;
return 0;
}
```
与C语言实现的代码基本相同,主要是用了C++的iostream库来输出结果。需要注意的是,赛德尔迭代只有在系数矩阵满足严格对角占优条件时才能保证收敛。否则可能会出现迭代不收敛的情况。
阅读全文