Gauss

mail@pastecode.io avatar
unknown
plain_text
16 days ago
1.9 kB
2
Indexable
Never
#include <bits/stdc++.h>
using namespace std;

void print(vector<vector<double>>& arr, int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n + 1; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    cout << "Enter the number of equations: " << endl;
    int n;
    cin >> n;
    vector<vector<double>> arr(n, vector<double>(n + 1));
    cout << "Enter the augmented matrix coefficients row-wise: " << endl;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n + 1; j++) {
            cin >> arr[i][j];
        }
    }

    for (int i = 0; i < n; i++) {
        // Partial Pivoting:
        if (arr[i][i] == 0) {
            bool row_swapped = false;
            for (int j = i + 1; j < n; j++) {
                if (arr[j][i] != 0) {
                    swap(arr[i], arr[j]);
                    row_swapped = true;
                    break;
                }
            }
            if (!row_swapped) {
                cout << "No unique solution exists due to zero diagonal element." << endl;
                return 0;
            }
        }

        for (int j = i + 1; j < n; j++) {
            double ratio = arr[j][i] / arr[i][i];
            for (int k = 0; k <= n; k++) {
                arr[j][k] -= ratio * arr[i][k];
            }
        }

        cout << "Matrix after step " << i + 1 << " of elimination:" << endl;
        print(arr, n);
    }

    // Back Substitution
    vector<double> x(n);
    for (int i = n - 1; i >= 0; i--) {
        x[i] = arr[i][n];
        for (int j = i + 1; j < n; j++) {
            x[i] -= arr[i][j] * x[j];
        }
        x[i] /= arr[i][i];
    }

    cout << "Solution is: " << endl;
    for (int i = 0; i < n; i++) {
        cout << "x" << i + 1 << " = " << x[i] << endl;
    }

    return 0;
}
/*3
 1 1 1 9
2 -3 4 13
3 4 5 40
*/
Leave a Comment