5

I`m trying to do this function that solves linear systems, A*x = b, where A = lower triangular matrix, linear independent matrix and with only one solution. But the results always show 0 0 0 0 ... I have printed the sum, s, and it always shows 0 as well...

 #include  <iostream>
 using namespace std;

void solve(int n, float a[][MAX], float b[], float x[]){
 int i,j;
 float s;

 for(i = 0; i < n; i++){
        s = 0;
        for(j = 0; j < n; j++){

            s = s + a[i][j]*x[j];
            cout<<s<<endl;
        }
    x[i] = (b[i] - s)/a[i][i];
 }
}
4pie0
  • 29,204
  • 9
  • 82
  • 118

2 Answers2

3
void solve(int n, float a[][MAX], float b[], float x[]){
  int i,j;
  float s;

  for(i = 0; i < n; i++) {
        s = 0;
        for(j = 0; j < i; j++) {
                       ^
            s = s + a[ i][ j] * x[ j];
        }
        x[ i] = ( b[ i] - s) / a[ i][ i];
   }
}

BackSubstitution.pdf

compiled example

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • the compiled example does not work (=not robust) for certain input. For instance, I enter $a[3][3]={0.2,-0.2,0,0,0.3,-0.2,0,0,0.25}$ and $b[3]={3,3,3}$. The codes compiles but leads to an incorrect answer as 15,10,12. Is it a way to fix the codes? – math101 Mar 12 '20 at 15:49
2

This line:

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

Should be:

    for(j = 0; j < i; j++){

Then it works fine - assuming your pivots are always non zero.

sbabbi
  • 11,070
  • 2
  • 29
  • 57
  • @lizusek Err... no? For instance when i=1 s should be A[1][0]*x[0] while in your code is simply 0. You have to sum all the A[i][j]*x[j] **on the left** of the diagonal, so basically for i < j. – sbabbi Mar 06 '14 at 23:15