Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- using namespace std;
- double** readMatrix(int n, char c) {
- double** matrix = new double*[n];
- for (int i = 0; i < n; i++) {
- matrix[i] = new double[n];
- }
- cout << endl << "Enter matrix " << c << " [" << n << "x" << n << "]:" << endl;
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- cin >> matrix[i][j];
- }
- }
- return matrix;
- }
- double* readArray(int n, char c) {
- double* array = new double[n];
- cout << endl << "Enter array " << c << " [" << n << "]:" << endl;
- for (int i = 0; i < n; i++) {
- cin >> array[i];
- }
- return array;
- }
- void solve(double** A, double* B, int n, double EPS) {
- double prevX[n] = { 0. }, X[n] = { 0. }, d;
- int i = 0;
- cout << endl;
- do {
- cout << "Iteration :: " << i << "\t >>\tx = {";
- for (int i = 0; i < n; i++) {
- prevX[i] = X[i];
- if (fabs(X[i]) > EPS) {
- cout << X[i];
- } else {
- cout << 0;
- }
- if (i != n - 1) {
- cout << ", ";
- }
- }
- cout << "}";
- for (int i = 0; i < n; i++) {
- X[i] = B[i];
- for (int j = 0; j < n; j++) {
- if (i != j) {
- if (j < i) {
- X[i] += -1 * A[i][j] * X[j];
- } else {
- X[i] += -1 * A[i][j] * prevX[j];
- }
- }
- }
- X[i] /= A[i][i];
- }
- d = fabs(X[0] - prevX[0]);
- for (int i = 1; i < n; i++) {
- if (fabs(X[i] - prevX[i]) > d) {
- d = fabs(X[i] - prevX[i]);
- }
- }
- cout << "\t >>\td = " << d;
- if (d < EPS) {
- cout << " < EPS";
- }
- cout << endl;
- i++;
- } while(d >= EPS);
- cout << endl << "RESULT :: x = {";
- for (int i = 0; i < n; i++) {
- cout << X[i];
- if (i != n - 1) {
- cout << ", ";
- }
- }
- cout << "}" << endl;
- }
- int main() {
- double EPS;
- int n;
- cout << "Enter n :: ";
- cin >> n;
- double** A = readMatrix(n, 'A');
- double* B = readArray(n, 'B');
- cout << endl << "Enter EPS: ";
- cin >> EPS;
- solve(A, B, n, EPS);
- for (int i = 0; i < n; i++) {
- delete[] A[i];
- }
- delete[] A;
- delete[] B;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement