数学上,高斯消元法,是线性代数规划中的一个算法,可用来为线性方程组求解。但其算法十分复杂,不常用于加减消元法,求出矩阵的秩,以及求出可逆方阵的逆矩阵。不过,如果有过百万条等式时,这个算法会十分省时。一些极大的方程组通常会用迭代法以及花式消元来解决。当用于一个矩阵时,高斯消元法会产生出一个“行梯阵式”。高斯消元法可以用在电脑中来解决数千条等式及未知数。亦有一些方法特地用来解决一些有特别排列的系数的方程组。
高斯消元法的原理是:
若用初等行变换将增广矩阵 化为 ,则AX = B与CX = D是同解方程组。
所以我们可以用初等行变换把增广矩阵转换为行阶梯阵,然后回代求出方程的解。
C++程序:(Dev C++)
#include <iostream>
#include <math.h>
#include<fstream>
using namespace std;class Mat {
public:Mat(int x, int y, double d[]) {rows = x;cols = y;if (x<y - 1)cout << "Not enough" << endl;int c = 0;for (int i = 0; i<x; i++) {for (int j = 0; j<y; j++) {data[i][j] = d[c];c++;}}}void print();int matcols();int matrows();void gauss();void change(int x);void result();
private:int rows;int cols;double data[200][200];};void Mat::print() {for (int i = 0; i<rows; i++) {for (int j = 0; j<cols; j++) {cout.width(4);cout << data[i][j] << " ";}cout << endl;}cout << endl;}int Mat::matcols() {return cols;
}int Mat::matrows() {return rows;
}void Mat::gauss() {double m = 0;double flag = 0;for (int i = 0; i<rows; i++) {change(i);print();if (data[i][i] != 0) {for (int j = i + 1; j<rows; j++) {//m = 1;if (data[j][i] == 0)continue;m = abs(1.0 * data[i][i] / data[j][i]);if ((data[j][i] > 0 && data[i][i] > 0) || (data[j][i] < 0 && data[i][i] < 0)) {flag = 1;}else{flag = -1;}for (int k = i; k<cols; k++) {data[j][k] = data[j][k] * m - flag*data[i][k];}print();}}}
}void Mat::change(int x) {double temp = 0;double max = abs(data[x][x]);int loc = x;for (int i = x; i < rows; i++) {if (abs(data[i][x]) > max) {max = abs(data[i][x]);loc = i;}}if (x != loc) {for (int i = x; i < cols; i++) {temp = data[x][i];data[x][i] = data[loc][i];data[loc][i] = temp;}}
}void Mat::result() {double ans[100] = {0};double sum = 0;for (int i = 1; i < cols; i++) {sum = data[cols - 1- i][cols -1 ];for (int j = 1; j < i; j++) {sum -= ans[cols - j] * data[rows - i][rows - j];}ans[cols - i] = sum / data[cols-1 - i][cols - 1 - i];}for (int i = 1; i < cols; i++) {cout << ans[i] << " ";}
}int main(int argc, char** argv) {double v[100000] = {};int n;int cc;
ifstream infile(",ios::in);int count =0;infile>>n;while(infile){infile>>cc;v[count] = cc;count++;}Mat a(n, n+1, v);a.print();a.gauss();a.print();a.result();return 0;
}
例:
文件1.txt:
3 1 2 4 17
1 1 1 6
2 1 2 10
输出:
1 2 3
本文发布于:2024-02-01 06:44:24,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170674106434645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |