2

Hi i use this code for gauss elimination method. when i use the second form of this algorithm i don't get the correct result, but in both cases the code is the same. so why this works:

for(k = 0 ; k < (n-1) ; k++) {

    for(i = k ; i < (n-1) ; i++) {

       temp = a[i+1][k]/a[k][k];  //Why?

       for(j = k ; j < n ; j++) {
            a[i+1][j] -=  a[k][j] * temp;
       }
   }
}

and this doesn't work:

for(k = 0 ; k < (n-1) ; k++) {

    for(i = k ; i < (n-1) ; i++) {

       for(j = k ; j < n ; j++) {

            a[i+1][j] -=  a[k][j] * a[i+1][k]/a[k][k];
       }
   }
}
2
  • 1
    In second case, firstly multiplication occurs, then the result is dividing. Commented Dec 23, 2014 at 14:57
  • Order Precedence Chart: swansontec.com/sopc.html left to right order: in your case, multiplication happens first, then the division operator. Commented Dec 23, 2014 at 14:57

2 Answers 2

4

In the second version, the innermost loop modifies the value of a[i+1][k]/a[k][k] as it's iterating.

To sidestep this, you have to factor out the expression as you've done in the first version.

Think about the reduced echelon form and about how Gaussian elimination works. One of the steps is to divide the entire row by the diagonal element, so that the diagonal element becomes one. If you don't save the original value of the diagonal element before diving it by itself, it will be lost for good.

Sign up to request clarification or add additional context in comments.

Comments

3

* and \ are of equal precedence. The associativity* of operators does matter in this case. Therefore in second case

 a[i+1][j] -=  a[k][j] * a[i+1][k]/a[k][k];  

will be treated as

 a[i+1][j] -=  (a[k][j] * a[i+1][k])/a[k][k];   

because when the operators are of equal precedence then left-to-right association takes place.

Parenthesize a[i+1][k]/a[k][k] and the second snippet will work

a[i+1][j] -=  a[k][j] * (a[i+1][k]/a[k][k]); 

*Associativity rules describe how an underparenthesized expression should be parenthesized when the expression has a bunch of the same kind of operator. For example, addition is associative from left to right, so a + b + c is equivalent to (a + b) + c, not a + (b + c). In ordinary arithmetic, these two expressions always give the same result; in computer arithmetic, they do not necessarily.

7 Comments

I was writing the same answer. You are faster than me.
that is another difference but still (a[k][j] * a[i+1][k])/a[k][k]; don't make second code == first code
oh I was wrong! you are correct that the second snippet will work after Parenthesize
This answer doesn't explain why the (a*b)/c is incorrect and a*(b/c) is correct. It only says that the result may be different. But which one is correct?
@anatolyg I believe this answers OP.. OP seems confuse and thinks both codes are equivalent.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.