⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gaussseidel.cpp

📁 这是数值分析中高斯赛德尔算法的实现程序。
💻 CPP
字号:
/***********************************************************/
/*                    Gauss-Seidel迭代法                         */
/***********************************************************/
#include "stdio.h"
#include "math.h"
#define n 3
//double A[n][n]={10,-2,-2,-2,10,-1,-1,-2,3};
//double b[n]={1,0.5,1};
////////////打印函数/////////////
void print1(char ar[2],double *arr)
{
	printf("%s is:",ar);
	for(int j=0;j<n;j++)				
	{	
		if(j==0) printf("\t[");
		printf("%16.9f",*(arr+j));
		if(j!=n-1) printf(",");
		else printf("\t]");
	}
	printf("\n");
}
///////求数组的最大值////////////
double arraymax(double *array)
{
	double max=0;
	int maxnum=0;
	for(int kk=0;kk<n;kk++)
		if(max<fabs(*(array+kk))) {max=fabs(*(array+kk));maxnum=kk;}
	//printf("maxnum is %d,max is %8.6f\n",maxnum,max);
	return max;
}

void GaussSeidel(double A[n][n],double b[n],double ee)
{
	int i,j;
	int count=0;
	double temp=0;
	double Mid[n]={0};
	double x[n]={0};
	double xx[n]={0};
	while(1)
	{
		for(i=1;i<=n;i++)
		{	
			temp=0;
			for(j=1;j<=i-1;j++)
			{	
				temp=temp+xx[j-1]*A[i-1][j-1]/A[i-1][i-1];
			}
			for(j=i+1;j<=n;j++)
			{
				temp=temp+x[j-1]*A[i-1][j-1]/A[i-1][i-1];
			}
			xx[i-1]=-temp+b[i-1]/A[i-1][i-1];
			Mid[i-1]=xx[i-1]-x[i-1];
			//print1("x",x);
			//print1("xx",xx);
			//print1("Mid",Mid);
		}
		print1("x",x);
		count++;
		if(arraymax(Mid)<=ee) break;
		else{
			for(i=0;i<n;i++)
				x[i]=xx[i];		
		}		
	}
	printf("count is %d\n",count);
	print1("the final x",x);
}

int main(int argc, char* argv[])
{
	double A[n][n]={5,2,1,-1,4,2,2,-5,10};
	double b[n]={-12,10,1};
	GaussSeidel(A,b,0.0001);
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -