迭代法求解线性方程组c语言
时间: 2023-06-21 13:15:22 浏览: 119
解线性方程组的迭代法.doc
以下是使用迭代法求解线性方程组的C语言代码:
```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], int max_iter, double tol)
{
int iter = 0;
double error = 0.0, sum = 0.0;
double x_new[N];
while (iter < max_iter)
{
for (int i = 0; i < N; i++)
{
sum = 0.0;
for (int j = 0; j < N; j++)
{
if (j != i)
{
sum += a[i][j] * x[j];
}
}
x_new[i] = (b[i] - sum) / a[i][i];
}
error = fabs(x_new[0] - x[0]);
for (int i = 0; i < N; i++)
{
error = fmax(error, fabs(x_new[i] - x[i]));
x[i] = x_new[i];
}
if (error < tol)
{
printf("Converged after %d iterations\n", iter + 1);
return;
}
iter++;
}
printf("Failed to converge after %d iterations\n", max_iter);
}
int main()
{
double a[N][N] = {{4.0, 1.0, -1.0},
{2.0, 7.0, 1.0},
{1.0, -3.0, 12.0}};
double b[N] = {3.0, -5.0, 14.0};
double x[N] = {0.0, 0.0, 0.0};
int max_iter = 1000;
double tol = 1e-6;
gauss_seidel(a, b, x, max_iter, tol);
for (int i = 0; i < N; i++)
{
printf("x[%d] = %g\n", i, x[i]);
}
return 0;
}
```
其中,`a`是系数矩阵,`b`是常数向量,`x`是待求解的未知向量。`max_iter`是最大迭代次数,`tol`是容差。在函数`gauss_seidel`中,使用了高斯-塞德尔迭代法求解线性方程组。循环中,每次更新`x_new`后,计算当前解的误差,如果误差小于容差,则认为已经收敛,函数返回。如果迭代次数达到最大值,但仍未收敛,则函数返回。最后在`main`函数中,给定系数矩阵、常数向量、初始解、最大迭代次数和容差,调用`gauss_seidel`函数求解线性方程组,并输出结果。
阅读全文