татата

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
3.0 kB
1
Indexable
Never
#include <iostream>
#include <math.h>
using namespace std;

double A_templ[3][3] =
{
{6, 1, 2},
{4, -6, 16},
{3, 8, 1}
};

double B_templ[3] =
{
21, 2, 2
};

void outputMatrix_dim1(double* matrix, double curr_dim)
{
for (int i = 0; i < curr_dim; i++)
{
cout « matrix[i] « " ";
}

cout « endl;
}

void outputMatrix_dim2(double** matrix, double curr_dim)
{
for (int i = 0; i < curr_dim; i++)
{
for (int j = 0; j < curr_dim; j++)
{
cout « matrix[i][j] « " ";
}

cout « endl;
}
}

bool checkConvergence(double** matrix, double curr_dim)
{
for (int i = 0; i < curr_dim; i++)
if (matrix[i][i] != 0)
return true;
else
return false;
}

void controlMethod(double** matrix_A, double* matrix_B, double* matrix_C, int curr_dim)
{
double curr_num;

for (int i = 0; i < curr_dim; i++)
{
curr_num = 0;

for (int j = 0; j < curr_dim; j++)
{
curr_num += matrix_A[i][j];
}

curr_num += matrix_B[i];
}
}

void gaussianMethod(double** matrix_A, double* matrix_B, double* matrix_C, int curr_dim)
{
double* arr_solutions = new double[curr_dim];
double n_main_diagonal;
double curr_n;

for (int i = 0; i < curr_dim; i++)
{
n_main_diagonal = matrix_A[i][i];

matrix_B[i] /= n_main_diagonal;
matrix_C[i] /= n_main_diagonal;

for (int h = i + 1; h < curr_dim; h++)
{
curr_n = matrix_A[h][i];
matrix_B[h] -= matrix_B[i] * curr_n;
matrix_C[h] -= matrix_C[i] * curr_n;
}

for (int j = 0; j < curr_dim; j++)
{
matrix_A[i][j] /= n_main_diagonal;

for (int h = i + 1; h < curr_dim; h++)
{
if (i == j)
curr_n = matrix_A[h][i];

matrix_A[h][j] -= matrix_A[i][j] * curr_n;
}

}
}

controlMethod(matrix_A, matrix_B, matrix_C, curr_dim);

if (checkConvergence(matrix_A, curr_dim))
{
arr_solutions[curr_dim - 1] = matrix_B[curr_dim - 1];

for (int i = curr_dim - 2; i >= 0; i--)
{
for (int j = curr_dim - 1; j > i; j--)
{
arr_solutions[i] = matrix_A[i][j] * arr_solutions[j];
}
arr_solutions[i] = matrix_B[i] - arr_solutions[i];
}

cout « "matrix A transformation" « endl;
outputMatrix_dim2(matrix_A, curr_dim);
cout « endl;

cout « "solutions" « endl;
outputMatrix_dim1(arr_solutions, curr_dim);
cout « endl;
}
else
cout « "Matrix does not converge" « endl;

}

int main()
{
int dim = 3;

double** A = new double* [dim];
for (int i = 0; i < dim; i++)
A[i] = new double[dim];

double* B = new double[dim];

double* C = new double[dim];

for (int i = 0; i < dim; i++)
for (int j = 0; j < dim; j++)
{
A[i][j] = A_templ[i][j];
}

B = B_templ;

for (int i = 0; i < dim; i++)
{
C[i] = 0;

for (int j = 0; j < dim; j++)
{
C[i] += A[i][j];
}

C[i] += B[i];
}
cout « "Matrix A" « endl;
outputMatrix_dim2(A, dim);
cout « endl;

cout « "Matrix B" « endl;
outputMatrix_dim1(B, dim);
cout « endl;

cout « "Odds column" « endl;
outputMatrix_dim1(C, dim);
cout « endl;

gaussianMethod(A, B, C, dim);
return 0;
}