Skip to content

Instantly share code, notes, and snippets.

@Yegorsh
Created December 21, 2021 20:53
Show Gist options
  • Select an option

  • Save Yegorsh/62e2d0a595f96cbd1cd26f2c05debe38 to your computer and use it in GitHub Desktop.

Select an option

Save Yegorsh/62e2d0a595f96cbd1cd26f2c05debe38 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
void FillMatrix(double **matrix, const int size){
for (int i=0; i<size; i++){
for (int j=0; j<size; j++){
matrix[i][j] = rand()%30;
}
}
}
void PrintMatrix(double **matrix, const int size){
for (int i=0; i<size; i++){
for (int j=0; j<size; j++){
cout << matrix[i][j] << "\t";
}
cout << endl;
}
}
void clearMemory(double** matrix, int size){
for (int i = 0; i < size; i++) {
delete[] matrix[i];
}
delete [] matrix;
}
int main(){
int size;
cout << "Порядок матрицы = ";
cin >> size;
cout << endl;
double **A = new double *[size];
for (int i = 0; i < size; i++) {
A[i] = new double [size];
}
FillMatrix(A,size);
if (A[0][0] == 0){
cout << "Невырожденная матрица A не имеет LU-разложения." << endl;
exit(0);
}
double **Lower = new double *[size];
for (int i = 0; i < size; i++) {
Lower[i] = new double [size];
}
double **Upper = new double *[size];
for (int i = 0; i < size; i++) {
Upper[i] = new double [size];
}
for (int i=0; i<size; i++){
for (int j=0; j<size; j++){
Upper[i][j] = 0;
Lower[i][j] = 0;
Lower[i][i] = 1;
}
}
for (int i=0; i<size; i++){
for (int j=0; j<size; j++){
if (i<=j){
double Sum = 0;
for (int k=0; k<=i-1; k++){
Sum += Lower[i][k] * Upper[k][j];
}
Upper[i][j] = A[i][j] - Sum;
}
else{
double Sum = 0;
for (int k=0; k<=j-1; k++){
Sum += Lower[i][k] * Upper[k][j];
}
Lower[i][j] = (A[i][j] - Sum) / Upper[j][j];
}
}
}
cout << "A = " << endl;
PrintMatrix(A,size);
cout << endl << "L = " << endl;
PrintMatrix(Lower,size);
cout << endl << "U = " << endl;
PrintMatrix(Upper,size);
clearMemory(A,size);
clearMemory(Lower,size);
clearMemory(Upper,size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment