开发者

A -1.0 / 1.0 operation returns a 0?

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:

  1. Isn't that code going to set everything from -infinity .. TOLERANCE to 0? That can't really be what you want.

  2. Shouldn't TOLERANCE be a very small number?

  3. 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.

  4. You might want to write the division as matrix[k][s] /= divisor;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜