松弛迭代法C程序
跪求各位大神 编写一个关于线性方程组的松弛迭代法C程序
/*
超松弛迭代求解线性方程组
*/
#include<stdio.h>
#include<math.h>
#define MAX_N 20 /*方程最大维数*/
#define MAXREPT 100
#define EPSILON 0.00001 /*求解精度*/
int main()
{
int n,i,j,k;
double err,w;
double a[MAX_N][MAX_N],b[MAX_N][MAX_N],c[MAX_N],g[MAX_N],x[MAX_N],nx[MAX_N];
printf("input n value(dim ofAX=C):"); /*输入方程的维数*/
while(scanf("%d",&n)==1&&n>0&&n<=MAX_N){ /*以0结束输入*/
printf("now input the matrix a(i),i=0,...,%d:\n",n-1);
for(i=0;i<n;i++) /*输入AX=C的A矩阵*/
for(j=0;j<n;j++)
scanf("%lf",&a[i][j]);
printf("now input the matrix c(i),i=0,..,%d:\n",n-1);
for(i=0;i<n;i++)
scanf("%lf",&c[i]);
printf("now input the w value:");
while(scanf("%lf",&w)!=1||w<1||w>2)
printf("w must between 1 and 2,please enter again.\n");
for(i=0;i<n;i++) /*改造x_{k+1}=bx_{k}+g迭代矩阵*/
for(j=0;j<n;j++){
b[i][j]=-a[i][j]/a[i][i];
g[i]=c[i]/a[i][i];
}
for(i=0;i<MAXREPT;i++){
for(j=0;j<n;j++)
nx[j]=g[j];
for(j=0;j<n;j++){
for(k=0;k<j;k++)
nx[j]+=b[j][k]*nx[k]; /*迭代*/
for(k=j+1;k<n;k++)
nx[j]+=b[j][k]*x[k];
nx[j]=(1-w)*x[j]+w*nx[j];
}
err=0;
for(j=0;j<n;j++)
if(err<fabs(nx[j]-x[j]))
err=fabs(nx[j]-x[j]); /*误差计算*/
for(j=0;j<n;j++)
x[j]=nx[j];
}
if(err<EPSILON){
printf("solve problem:x_i=\n");
for(i=0;i<n;i++)
printf("%lf ",x[i]);
printf("\n");
}
continue;
printf("after %d repeat,no result...\n",MAXREPT);
}
return 0;
}