基于C++的n阶线性方程组Ax=b求解

基于C++的n阶线性方程组Ax=b求解:

bool CUtil::Solve(double** A, double* b, double* x, int n)
{  


	double** M = new double*[n];  
	for (int i=0; i<n; i++)  
	{  
		M[i] = new double[n+1];  
		for (int j=0; j<n; j++)  
		{  
			M[i][j] = A[i][j];  
		}  
		M[i][n] = b[i];  
	}  
	for (int k=0; k<n; k++)  
	{//n个主元  
		double colMax = fabs(M[k][k]);  
		int maxLineIndex = k;  
		for(int i=k+1; i<n; i++)  
		{//寻找第k列的最大元素  
			if(fabs(M[i][k]) > colMax)  
			{  
				colMax = fabs(M[i][k]);  
				maxLineIndex = i;  
			}  
		}  
		if(colMax < EPSILONG)  
		{//奇异矩阵  
			for (int i=0; i<n; i++)  
			{  
				delete M[i];  
			}  
			delete M;  
			return false;  
		}  
		double temp;  
		//交换k行和maxLineIndex行  
		for (int m=0; m<n+1; m++)  
		{  
			temp = M[k][m];  
			M[k][m] = M[maxLineIndex][m];  
			M[maxLineIndex][m] = temp;  
		}  


		//消去  
		for(int i=k+1; i<n; i++)  
		{  
			for (int j=k+1; j<n+1; j++)  
			{  
				M[i][j] = M[k][k]*M[i][j]/M[i][k] - M[k][j];  
			}  
		}  
	}  
	//回归求解  
	for (int i=n-1; i>=0; i--)  
	{  
		x[i] = M[i][n];  
		for (int j=i+1; j<n; j++)  
		{  
			x[i] -= M[i][j]*x[j];  
		}  
		x[i] /= M[i][i];  
	}  
	for (int i=0; i<n; i++)  
	{  
		delete M[i];  
	}  
	delete M;  
	return true;  
}


你可能感兴趣的:(C++,算法,线性方程组,n阶线性方程组)