高斯消去法是求解线性方程组常用的直接解法

高斯(Gauss)消去法解方程组的基本思想是用矩阵的行初等变换将系数矩阵约化为上三角形矩阵,再进行回代求解。

设Ax=b,A \in R^{n\times n},若A的所有顺序主子式均不为零,则基本高斯消元无需换行进行到底,得到唯一解,其消元和回代的计算公式为:

(1)消元计算     对于 k=1,2,\cdots ,n-1,

m_{ik}=\frac{a_{ik}^{(k)}}{a_{kk}^{(k)}} ,i=k+1,\cdots ,n, 

a_{ij}^{(k+1)}=a_{ij}^{(k)}-m_{ik}{a_{kj}^{(k)} ,b_{i}^{(k+1)}=b_{i}^{(k)}-m_{ik}{b_{k}^{(k)} ,i=k+1,\cdots ,n.

(2)回代计算

x_{n}=\frac{b_{n}^{(n)}}{a_{nn}^{(n)}} ,x_{i}=\frac{b_{i}^{(i)}-\sum_{j=i+1}^{n}a_{ij}^{(i)}x_{j}}{a_{ii}^{(i)}},i=n-1,\cdots ,1.

基本高斯消去法c++代码:此程序编写的函数用的容器作为参数传递,不用定义A系数的矩阵大小。

#include "pch.h"
#include <iostream>//基本数据流输入/输出
#include <iomanip> //参数化输入/输出 
#include <vector>//STL动态数组容器
using namespace std;
//************************
//高斯消去法公式
//***********************
vector<double> gaussian_elimination(vector<vector<double>>a, vector<double>b); //高斯消去法求解线性方程组AX=B
vector<double> gaussian_elimination(vector<vector<double>>a, vector<double>b)
{
	int n = size(b);
	vector<double>x;    //定义方程组解
	x.resize(n);
	vector<double>mi_k; //定义消去过程中的中间变量
	mi_k.resize(n);
	double sum;
	for (int i = 0; i < n; i++)
	{
		//判断能否用高斯消去法
		if (a[i][i] == 0)
		{
			cout << "can't use Gaussian meathod" << endl;
		}
	}
	//n-1步消元
	for (int k = 0; k < n - 1; k++)
	{
		//求出第i次初等行变换系数
		for (int j = k + 1; j < n; j++)
		{
			mi_k[j] = a[j][k] / a[k][k];
		}
		for (int i = k + 1; i < n; i++)
		{
			for (int j = 0; j < n; j++)
			{
				a[i][j] = a[i][j] - mi_k[i] * a[k][j];
			}
			b[i] = b[i] - mi_k[i] * b[k];
		}
	}	//回代过程
	x[n - 1] = b[n - 1] / a[n - 1][n - 1];
	for (int i = n - 2; i >= 0; i--)
	{
		sum = 0;
		for (int j = i + 1; j < n; j++)
		{
			sum = sum + a[i][j] * x[j];
		}
		x[i] = (b[i] - sum) / a[i][i];
	}
	return x;
}
int main()
{
	vector<vector<double>>a;
	a.resize(3, vector<double>(3));
	vector<double>b(3);
	vector<double>x;
	a[0] = { 0.5,1.1,3.1 }, a[1] = { 2.0,4.5,0.36 }, a[2] = { 5.0,0.96,6.5 };
	b = { 6.0,0.02,0.96 };

	x = gaussian_elimination(a, b);
	cout << "解为:" << endl;
	for (int i = 0; i < 3; i++)
		cout <<"x["<<i<<"]="<< fixed << setprecision(2) << setw(5) << x[i] << endl;
}

运行结果:

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐