gaussseidel迭代法c++
时间: 2023-12-25 09:04:21 浏览: 9
Gauss-Seidel迭代法是一种求解线性方程组的方法,可以用来解决大规模的稠密线性方程组。下面是使用C语言实现Gauss-Seidel迭代法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 3
void gauss_seidel(double A[N][N], double b[N], double x[N], double eps, int max_iter)
{
int i, j, k, iter;
double sum;
for (iter = 0; iter < max_iter; iter++) {
for (i = 0; i < N; i++) {
sum = 0.0;
for (j = 0; j < N; j++) {
if (j != i) {
sum += A[i][j] * x[j];
}
}
x[i] = (b[i] - sum) / A[i][i];
}
// 检查误差是否小于指定的eps
sum = 0.0;
for (i = 0; i < N; i++) {
double tmp = 0.0;
for (j = 0; j < N; j++) {
tmp += A[i][j] * x[j];
}
tmp -= b[i];
sum += tmp * tmp;
}
if (sqrt(sum) < eps) {
printf("Converged after %d iterations\n", iter + 1);
return;
}
}
printf("Did not converge after %d iterations\n", max_iter);
}
int main()
{
double A[N][N] = {
{10.0, -1.0, 2.0},
{-1.0, 11.0, -1.0},
{2.0, -1.0, 10.0}
};
double b[N] = {6.0, 25.0, -11.0};
double x[N] = {0.0, 0.0, 0.0};
double eps = 1e-6;
int max_iter = 1000;
gauss_seidel(A, b, x, eps, max_iter);
printf("Solution:\n");
for (int i = 0; i < N; i++) {
printf("x[%d] = %f\n", i, x[i]);
}
return 0;
}
```
这段代码实现了对线性方程组 Ax=b 进行求解,其中A是一个3x3的系数矩阵,b是一个长度为3的常数向量,x是未知向量。在求解过程中,我们采用Gauss-Seidel迭代法进行迭代求解,并且设置了最大迭代次数为1000次,误差限为1e-6。最终输出求解结果。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)