#include #include #include using namespace std; //Findine matrix's minors void GetMinor(vector > A, vector > &B, int x, int y, int size) { int _x = 0; int _y; for (int i = 0; i < size; ++i) { if (i != x) { _y = 0; for (int j = 0; j < size; ++j) { if (j != y) { B[_x][_y] = A[i][j]; _y++; } } _x++; } } } //Finding determinant of matrix (size x size) double FindDeterminant(vector > A, int size) { if (size == 1) { return A[0][0]; } else { double det = 0; vector > Minor(size - 1, vector (size - 1)); for (int i = 0; i < size; ++i) { GetMinor(A, Minor, 0, i, size); det += pow(-1, i) * A[0][i] * FindDeterminant(Minor, size - 1); } return det; } } double InsertFreeCoeff(vector > A, vector B, int size, int j) { for (int i = 0; i < size; ++i) { A[i][j] = B[i]; } double det = FindDeterminant(A, size); return det; } int n = 2; double eps = 0.0001; bool converge(vector a, vector b) { double norm = 0; for (int i = 0; i < n; i++) { norm += (a[i] - b[i])*(a[i] - b[i]); } if (sqrt(norm) >= eps) return false; return true; } void main() { int N = 0; cout << "Enter size matrix: "; cin >> N; vector > A(N, vector (N)); vector B(N); cout << "Enter coefficients a[i][j]: " << endl; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { cout << "a[" << i + 1 << "][" << j + 1 << "] = "; cin >> A[i][j]; } cout << "\n"; } cout << "\n"; cout << "Enter free coefficients b[i]: " << endl; for (int i = 0; i < N; ++i) { cout << "b[" << i + 1 << "] = "; cin >> B[i]; } cout << "\n"; //CAAAAASE int key; cout << "1. Cramer. 2.Relax: "; cin >> key; switch (key) { case 1: { cout << "Linear system equation:" << endl; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) cout << A[i][j] << " * X" << j + 1 << "\t"; cout << " = " << B[i] << "\n"; } cout << endl; double det = FindDeterminant(A, N); if (det == 0) { cout << ">>>No roots!<<<" << endl; } else { cout << "det_A: " << det << endl; cout << "\n"; for (int i = 0; i < N; ++i) { cout << "det_" << i << " = " << InsertFreeCoeff(A, B, N, i) << "\n"; } cout << endl; cout << "Roots: " << endl; for (int i = 0; i < N; ++i) { cout << "X" << i + 1 << " = " << InsertFreeCoeff(A, B, N, i) / det << "\n"; } } break; } case 2: { double omega; cout << "Enter omega: "; cin >> omega; cout << endl; int k=0; //previous values vector x_prev(N); vector x_curr(N,0.0); do { k++; printf("%d. ", k); for (int i = 0; i < N; i++) x_prev[i] = x_curr[i]; for (int i = 0; i < N; i++) { double var = 0; for (int j = 0; j < i; j++) var = var + (A[i][j] * x_curr[j]); for (int j = i + 1; j < N; j++) var = var + (A[i][j] * x_prev[j]); x_curr[i] = (1 - omega) * x_prev[i] + omega / A[i][i] * (B[i] - var); printf("%.8f \t", x_prev[i]); } cout << endl; } while (!converge(x_curr, x_prev)); cout << k << endl; } } cout << "\n"; system("pause"); }