Created
November 14, 2018 06:24
-
-
Save Chillee/35236efaf02b1b0e333c4fb8a0caa9e4 to your computer and use it in GitHub Desktop.
Gaussian Elimination
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| int gauss(vector<vector<double>> a, vector<double> &ans) { | |
| const double EPS = 1e-6; | |
| int n = (int)a.size(); | |
| int m = (int)a[0].size() - 1; | |
| vector<int> where(m, -1); | |
| for (int col = 0, row = 0; col < m && row < n; ++col) { | |
| int sel = row; | |
| for (int i = row; i < n; ++i) | |
| if (abs(a[i][col]) > abs(a[sel][col])) | |
| sel = i; | |
| if (abs(a[sel][col]) < EPS) | |
| continue; | |
| for (int i = col; i <= m; ++i) | |
| swap(a[sel][i], a[row][i]); | |
| where[col] = row; | |
| for (int i = 0; i < n; ++i) | |
| if (i != row) { | |
| double c = a[i][col] / a[row][col]; | |
| for (int j = col; j <= m; ++j) | |
| a[i][j] -= a[row][j] * c; | |
| } | |
| ++row; | |
| } | |
| ans.assign(m, 0); | |
| for (int i = 0; i < m; ++i) | |
| if (where[i] != -1) | |
| ans[i] = a[where[i]][m] / a[where[i]][i]; | |
| for (int i = 0; i < n; ++i) { | |
| double sum = 0; | |
| for (int j = 0; j < m; ++j) | |
| sum += ans[j] * a[i][j]; | |
| if (abs(sum - a[i][m]) > EPS) | |
| return 0; | |
| } | |
| for (int i = 0; i < m; ++i) | |
| if (where[i] == -1) | |
| return -1; | |
| return 1; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment