本文主要是介绍高斯消元(完全主元法 and 部分主元法) C++代码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
部分主元法高斯消元
/*
算法步骤:1.枚举每一列,找到绝对值最大的一行2.将该行和第一行交换3.将该行行首置为一4.将下面所有行第 i 列置为零
*/#include <iostream>
#include <cmath>using namespace std;
const int N = 109;
const double eps = 1e-6;
double a[N][N];
int n;// 未知数个数, 方程数量
void init()
{// cout << "未知数的个数,方程的数量: ";cin >> n;for (int i = 0; i < n; i++)for (int j = 0; j < n + 1; j++)cin >> a[i][j];
}
bool Gauss()
{int l = 0, r = 0; //行 列// step 1 and 2for (l = 0, r = 0; r < n; r++){int tt = l;for (int i = l; i < n; i++)if (fabs(a[tt][r]) < fabs(a[i][r]))tt = i;if (fabs(a[tt][r]) < eps) continue;for (int i = r; i < n + 1; i++)swap(a[tt][i], a[l][i]); // step 3for (int i = n; i >= r; i--)a[l][i] /= a[l][r];// step 4 将下面所有行第 r 列置为零for (int i = l + 1; i < n; i++){if (fabs(a[i][r]) < eps) continue;for (int j = n; j >= r; j--)a[i][j] -= a[l][j] * a[i][r];}l++;}for (int i = n - 1; i >= 0; i--)for (int j = i + 1; j < n; j++)a[i][n] -= a[j][n] * a[i][j];if (l == n) return 0;return 1;
}
int main()
{init();if (!Gauss())for (int i = 0; i < n; i++)cout << "x" << i << " = "<< a[i][n] << '\n';elsecout << "无解!!!\n";
}/*
3
1 1 1 6
0 4 -1 5
2 -2 1 1
*/
完全主元法高斯消元
#include <bits/stdc++.h>
using namespace std;
#define PII pair<int, int>
const int N = 109;
const double eps = 1e-6;
double a[N][N];
int id[N];
int n;void init()
{cin >> n;for (int i = 0; i < n; i++) id[i] = i;for (int i = 0; i < n; i++)for (int j = 0; j < n + 1; j++)cin >> a[i][j];
}
PII Get_Max_Idx(int l, int r)
{PII idx;double mx = 0;for (int i = l; i < n; i++)for (int j = r; j < n; j++)if (fabs(a[i][j]) > mx)mx = fabs(a[i][j]), idx = {i, j};return idx;
}
bool Gauss()
{int l = 0, r = 0;for (l = 0, r = 0; r < n; r++){PII tt = Get_Max_Idx(l, l);//行交换for (int i = r; i < n + 1; i++)swap(a[tt.first][i], a[l][i]);tt.first = l;//列交换for (int i = 0; i < n; i++)swap(a[i][tt.second], a[i][r]);swap(id[tt.second], id[r]);// step 3for (int i = n; i >= r; i--)a[l][i] /= a[l][r];// step 4 将下面所有行第 r 列置为零for (int i = l + 1; i < n; i++){if (fabs(a[i][r]) < eps) continue;for (int j = n; j >= r; j--)a[i][j] -= a[l][j] * a[i][r];}l++;}for (int i = n - 1; i >= 0; i--)for (int j = i + 1; j < n; j++)a[i][n] -= a[j][n] * a[i][j];if (l == n) return 0;return 1;
}
int main()
{init();if (!Gauss()){for (int i = 0; i < n; i++)cout << "x" << id[i] << " = "<< a[i][n] << '\n';}else cout << "无解!!!\n";
}
这篇关于高斯消元(完全主元法 and 部分主元法) C++代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!