Jacobi迭代,G-S迭代和超松弛迭代法解线性方程组(C语言)

Jacobi迭代,G-S迭代在注释中,当前为超松弛迭代法。

#include 
#include 
#define N 105
float A[N][N];
float b[N];
int DT=0;
float two_norm(float x[],float y[],int n);
float one_norm(float x[],float y[],int n);
void GSS_iteration(float y[],int n);
float abs(float a);
FILE *fp=fopen("data.txt","w");

int main(void)
{
	//FILE *fp;
	int i,j,k;
	float initial_x[N];
	float eps,h,a;
	int n=100;
	h=0.01;
	for (i=1;i<=n;i++)
	{
		b[i]=0.5*0.01*0.01;
    }
	b[n]=b[n]-0.01-0.01;
	
	for (i=1;i<=n;i++)
	{
		initial_x[i]=0.01*i;
	}
	
	for (i=1;i<=n;i++)
	{
		for (j=1;j<=n;j++)
		{
			A[i][j]=0.0;
		}
	}
	
	printf("Please enter the eps and the right number a:\n");
	scanf("%f %f",&eps,&a);
	
	for (i=1;i<=n;i++)
	{
		A[i][i]=-2*eps-h;
	}
	for (i=1;i<=n-1;i++)
	{
		A[i+1][i]=eps;
	}
	for (i=2;i<=n;i++)
	{
		A[i-1][i]=eps+h;
	}
	
	for (i=1;i<=n;i++)
	{
		for (j=1;j<=n;j++)
		{
			printf("%f ",A[i][j]);
		}
		printf("\n");
	}
	
	for (i=1;i<=n;i++)
	{
		printf("%f ",b[i]);
	}
	printf("\n");
	
	GSS_iteration(initial_x,n);
	
	return 0;
}


float two_norm(float x[],float y[],int n)
{
	float norm=0.0;
	int i,j;
	
	for (i=1;i<=n;i++)
	{
		norm+=(x[i]-y[i])*(x[i]-y[i]);
	}
	
	return norm;
}

float one_norm(float x[],float y[],int n)
{
	float norm=0.0;
	int i,j;
	float max=abs(x[1]-y[1]);
	for (i=1;i<=n;i++)
	{
		if (abs(x[i]-y[i])>max)
		{
			max=abs(x[i]-y[i]);
		}
	}
	return max;
}

float abs(float a)
{
	if (a>=0)
	{
		return a;
	}
	else 
	return -a;
}

void GSS_iteration(float y[],int n)
{
	int i,j,k;
	float sum=0.0;
	float resi;
	float x[N];
	float residual=0.00001; 
	

	
	for (i=1;i<=n;i++)
	{
		sum=0.0;
		for (j=1;j<=n;j++)
		{
			/*
			if (j==i)
			{
				continue;
			}
			else
			sum+=A[i][j]*y[j];//Jacobi迭代 
			*/
			for (j=1;j<=i-1;j++)
			{
				sum+=A[i][j]*x[j];
			}
			for (j=i+1;j<=n;j++)
			{
				sum+=A[i][j]*y[j];
			}
			
		}
		x[i]=0.7*y[i]+0.3*(b[i]-sum)/A[i][i];
	}
	
	//判断迭代是否终止.
	y[n]=1;
	resi=one_norm(x,y,n);
	if (resi3000)
	{
		//resi=one_norm(x,y,n);
		printf("The residual is :%f\n",resi);
		for (i=1;i<=n;i++)
		{
			printf("%f ",y[i]);
			fprintf(fp,"%f ",y[i]);
		}
		fclose(fp);
		return ;
	}
	
	else
	{
		GSS_iteration(x,n);
	}
	return ;
}

 

你可能感兴趣的:(C语言,线性方程组,迭代法)