Gauss-Jordan Elimination Inverse Matrix

This is the calculation part of my code. Other parts are just inputting and outputting so I don't post here. My problem is that sometimes, the output I have is nan due to divide by 0.
Here is one example:
1 2 2
1 2 1
0 2 4

1
2
3
4
5
6
7
8
9
10
11
12
13
for(int i=0; i<n; i++){
  tmp = A[i][i];
  for(int j=i; j<2*n; j++)
    A[i][j] = A[i][j]/tmp;
  for(int j=0; j<n;j++){
    if(i!=j){
      tmp=A[j][i];
      for(int k=0; k<2*n; k++){
        A[j][k] = A[j][k] - (tmp*A[i][k]);
      }
    }
  }
}
Hi,

A question:

What is the type of A? int could be problematic

Is integer division going to give you the right results? Consider making the type double. :+)

If you have any division operations anywhere, it's wise to explicitly check with code if the denominator is not zero or close enough to zero to warrant it being a problem for what you are doing. Unless you are sure it is OK: you checked all the values in a container were valid. For example with the near to zero value: in one formula a value less than 0.001 might be considered near enough to zero: in another, 1e-6 might be more appropriate.

If the value is near enough to zero, then your code needs to decide what to do about it.

Hope this helps :+)

I'm pretty sure I declare it as double!!
Ah Good :+)

I am sorry, I made a big assumption about that.

But this part still applies:

If the value is near enough to zero, then your code needs to decide what to do about it.


Not only to not do the division, but also determine what that means in terms of the algorithm.

Good Luck!!
Topic archived. No new replies allowed.