线性方程组的迭代解法c语言实现

线性方程组的迭代解法

线性方程组的迭代解法 C语言实现

至少选择雅可比迭代法、高斯-赛德尔迭代法上述方法中的一种方法(鼓励多选)对下列方程组进行求解。线性方程组的迭代解法c语言实现_第1张图片
精度要求10-3

//雅可比迭代法:
#include
#include
double fx1(double x2,double x3){
	double x1=0.1*x2+0.2*x3+0.72;
	return x1;
}
double fx2(double x1,double x3){
	double x2=0.1*x1+0.2*x3+0.83;
	return x2;
}
double fx3(double x1,double x2){
	double x3=0.2*x1+0.2*x2+0.84;
	return x3;
}
double max(double x1,double x2,double x3,double a,double b,double c){
	double max=0,m;
	if(fabs(a-fx1(x2,x3))>fabs(b-fx2(x1,x3))){
		m=fabs(a-fx1(x2,x3));
	} else m=fabs(b-fx2(x1,x3));
	if(m>fabs(c-fx3(x1,x2))){
		max=m;
	}else max=fabs(c-fx3(x1,x2));
	return max;
}

int main(){
	double x1,x2,x3,a,b,c;
	int n=0;
	printf("输入初值x1,x2,x3\n");
	scanf("%f %f %f",&x1,&x2,&x3);
	a=x1;
	b=x2;
	c=x3;
	while(max(x1,x2,x3,a,b,c)>0.001){
		a=fx1(x2,x3);
		b=fx2(x1,x3);
		c=fx3(x1,x2);
		x1=a;
		x2=b;
		x3=c;
		n++;
		printf("%f\t%f\t%f\t\n",x1,x2,x3);
	}
	printf("迭代次数:%d\n",n); 
	printf("结果为 x1=%f\t x2=%f\t x3=%f\t",x1,x2,x3);
}
//高斯-赛德尔迭代法:
#include
#include
double fx1(double x2,double x3){
	double x1=0.1*x2+0.2*x3+0.72;
	return x1;
}
double fx2(double x1,double x3){
	double x2=0.1*x1+0.2*x3+0.83;
	return x2;
}
double fx3(double x1,double x2){
	double x3=0.2*x1+0.2*x2+0.84;
	return x3;
}
double max(double x1,double x2,double x3){
	double max=0,m;
	if(fabs(x1-fx1(x2,x3))>fabs(x2-fx2(x1,x3))){
		m=fabs(x1-fx1(x2,x3));
	} else m=fabs(x2-fx2(x1,x3));
	if(m>fabs(x3-fx3(x1,x2))){
		max=m;
	}else max=fabs(x3-fx3(x1,x2));
	return max;
}

int main(){
	double x1,x2,x3,a,b,c;
	int n=0;
	printf("输入初值x1,x2,x3\n");
	scanf("%f %f %f",&x1,&x2,&x3);
	
	while(max(x1,x2,x3)>0.001){
		x1=fx1(x2,x3);
		x2=fx2(x1,x3);
		x3=fx3(x1,x2);
		n++;
		printf("%f\t%f\t%f\t\n",x1,x2,x3);
	}
	printf("迭代次数:%d\n",n); 
	printf("结果为 x1=%f\t x2=%f\t x3=%f\t",x1,x2,x3);
}

第一次写博客,代码是自己编写的,仅供参考。

你可能感兴趣的:(c语言)