高斯消去法,其实就是利用初等变换把矩阵转换成上三角,便于求行列式,求逆,求线性方程组的解
只要动笔演算一下相关矩阵元素的索引,就能使得核心代码特别短,
初等变换如下
for (int i = 0; i < column - 1; i++) { for (int j = 0; j < row - 1 - i; j++) { double coef = *(matrix + (row - 1 - j)*column + i) / *(matrix + i * column + i); for (int k = 0; k < column; k++) { *(matrix + (row - 1 - j)*column + k) -= (coef*(*(matrix + i * column + k))); } } }
方程求解代码如下:
double* result = new double[column-1]; for(int i=0;i<column-1;i++){ double temp = 0; for(int j=0;j<i;j++){ temp += *(matrix+(column-2-i)*column+column-1-i+j)*(*(result+column-1-i+j)); } *(result+column-2-i) = (*(matrix+(column-2-i)*column+column-1) - temp) / *(matrix+(column-2-i)*column+column-2-i); }
完整代码给出如下:
#include <iostream> void printMatrix(double *matrix, int row, int column) { for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { printf("%6.2lf ", *(matrix + i * column + j)); } printf(" "); } } void printVector(double *matrix, int len) { for (int i = 0; i < len; i++) { printf("%6.2lf, ", *(matrix + i)); } printf(" "); } void gaussianElimination(double *matrix, int row, int column) { int i,j; for (i = 0; i < column - 1; i++) { for (j = 0; j < row - 1 - i; j++) { //printf("分母%lf,分子%lf ", *(matrix + i * column + i), *(matrix + (row - 1 - j)*column + i)); double coef = *(matrix + (row - 1 - j)*column + i) / *(matrix + i * column + i); //printf("系数:%lf,", coef); for (int k = 0; k < column; k++) { //printf("%lf -= %lf * %lf ", *(matrix + (row - 1 - j)*column + k), coef, *(matrix + i * column + k)); *(matrix + (row - 1 - j)*column + k) -= (coef*(*(matrix + i * column + k))); //printf("%lf ", *(matrix + (row - 1 - j)*column + k)); } } //printf(" "); } printMatrix(matrix, row, column); double* result = new double[column-1]; for(i=0;i<column-1;i++){ double temp = 0; for(j=0;j<i;j++){ temp += *(matrix+(column-2-i)*column+column-1-i+j)*(*(result+column-1-i+j)); } *(result+column-2-i) = (*(matrix+(column-2-i)*column+column-1) - temp) / *(matrix+(column-2-i)*column+column-2-i); } printf("求得方程的解为:"); printVector(result, column-1); if(result){ delete[] result; } }
用主函数测试一下正确性
int main() {double matrix[] = {1,1,0,3,4, 2,1,-1,1,1, 3,-1,-1,2,-3, -1,2,3,-1,4}; int row = 4, column = 5; gaussianElimination(matrix, row, column); return 0; }
结果如下,显然正确