I'm writing a program that solves matrices by Gauss-Jordan method. Everything works except for -1.0/1.0. When printing the matrix, it prints out a 0.0 when it should still be -1.0. Can anyone explain why this is happening? In the case below, matrix[k][s] is -1.0 and the divisor is a 1.0 double value.
for(s 开发者_Go百科= 0; s < (n+1); s++){ //Augmented matrix, while s < number of columns
                    if(divisor == 0.0){ //Not dividing by 0.0
                            continue;
                    }
                    matrix[k][s] = matrix[k][s] / divisor;
                    if((matrix[k][s] < TOLERANCE) || (matrix[k][s] < -TOLERANCE)){ //To avoid -0.0 values, TOLERANCE == 1e6
                            matrix[k][s] = 0.0;
                    }
My guess is that you wanted this condition:
(matrix[k][s] < TOLERANCE) || (matrix[k][s] < -TOLERANCE)
to be this:
(matrix[k][s] < TOLERANCE) && (matrix[k][s] > -TOLERANCE)
In other words, when fabs(matrix[k][s]) < TOLERANCE
(Note to explain comments in other answers - I originally used abs, but fabs is the correct function here.)
if ((matrix[k][s] < TOLERANCE) || (matrix[k][s] < -TOLERANCE))
does not do what you want it to.  In particular, if matrix[k][s] is -1.0, this condition is true.  Instead, you want:
if (fabs(matrix[k][s]) < TOLERANCE)
|| should be && ?
if (fabs(matrix[k][s]) < TOLERANCE)
Edit ref Jon's answer; abs(matrix[k][s]) < TOLERANCE is right solution..
I can see a few issues:
- Isn't that code going to set everything from -infinity .. TOLERANCE to 0? That can't really be what you want. 
- Shouldn't TOLERANCE be a very small number? 
- Is the comparison with 0.0 really necessary? On modern processors, a division by 0 should produce an infinity and should not produce an exception. 
- You might want to write the division as - matrix[k][s] /= divisor;
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论