Seidel迭代法
程序员文章站
2022-06-07 09:46:22
...
PS:e为误差值,自己设定
#include<stdio.h>
#include<math.h>
#define N 3
#define col 3//列数
#define row 3//行数
void print(double a[row][col]) {
for (int i = 0; i < row; i++)//找到最大主元,记录行号和列号
{
for (int j = 0; j < col; j++)
{
printf("%f ", a[i][j]);
}
printf("\n");
}
printf("\n");
}
void printXY(double XY[N]) {
for (int i = 0; i < N; i++)
{
printf("%f ", XY[i]);
}
printf("\n\n");
}
void Seidel(double X[N],double b[N], double a[N][N],double e)
{
double p;
for (int i = 1; i <=N; i++)
{
X[i-1] = 0;
}
do
{
p = 0;
for (int i = 1; i <= N; i++)
{
double t = X[i-1];
double sum = 0;
for (int j = 1; j <= N; j++)
{
if (j == i)
continue;
sum += a[i-1][j-1] * X[j-1];
}
X[i - 1] = (b[i - 1] - sum) / a[i - 1][i - 1];
if (fabs(X[i - 1] - t) > p)
p = fabs(X[i-1] - p);
}
}
while (p>e);
}
int main()
{
double a[N][N] = { { 4,3,0},
{ 3,4,-1 },
{ 0,-1,4 },
},
b[N] = {24,30,-24}, X[N] = { 0 },e=0;
Seidel(X,b,a,e);
printXY(X);
getchar();
}