K
K
kornietsbk2020-04-30 22:45:33
C++ / C#
kornietsbk, 2020-04-30 22:45:33

Why does the calculation of a triangular matrix by the Gauss-Jordan method work through time?

The program calculates a triangular matrix higher than the second order (in what follows, we will calculate the diagonal along the diagonal).
I will implement the processing of zeros on the diagonal later. The matrix is ​​filled in such a way that there are no zeros anywhere.
The calculation of the matrix is ​​more accurate when the matrix is ​​of a smaller order or when the matrix is ​​filled with numbers that are "convenient" for calculation.
Sometimes the value of the matrix element = -0, and sometimes the subtraction does not occur
Tell me how to make it work as it should?

#include <iostream>
#include <time.h>


int main(){
    srand(time(nullptr));

    float** mtrx;
    int power;
    std::cout<<"Enter power: ";
    std::cin>>power;


    mtrx = new float*[power];
    for(int i = 0; i < power; i++){
        mtrx[i] = new float[power];
        for(int j = 0; j < power; j++){
            mtrx[i][j] = rand()%10 + 1;
        }
    }
    std::cout<<"Matrix:"<<std::endl;
    for(int i = 0; i < power; i++){
        for(int j = 0; j < power; j++){
            std::cout<<mtrx[i][j]<<" ";
        }
        std::cout<<std::endl;
    }
    std::cout<<std::endl<<std::endl;


    for(int col = 0; col < power-1; col++){
        for(int str = power-1; str>0; str--){
            if(mtrx[str][col] != 0.0){
                if(str - 1 >= 0 && mtrx[str-1][col] != 0){
                    float coeff = mtrx[str][col]/mtrx[str-1][col];
                    std::cout<<"Coeff: "<<coeff<<std::endl;
                    for(int col_num = 0; col_num < power ;col_num++){
                        mtrx[str - 1][col_num] *= coeff;
                    }
                    for(int col_num = col;col_num <str; col_num++){
                        mtrx[str][col_num] -= mtrx[str-1][col_num];
                    }
                }
            }
            
    }


    




    for(int i = 0; i < power; i++){
        for(int j = 0; j < power; j++){
            std::cout<<mtrx[i][j]<<" ";
        }
        std::cout<<std::endl;
    }


    return 0;
}
<code lang="cpp">

</code>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hint000, 2020-05-01
@hint000

Just a couple of comments.
Firstly, in a line if(str - 1 >= 0 && mtrx[str-1][col] != 0){, you can throw str - 1 >= 0 unrestrictedly, this condition is always met for you, because two lines above the loop execution condition: str>0;
Second, use double instead of float and the results of the program will miraculously improve.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question