Home > Back-end >  Gauss-Jacobi iteration method
Gauss-Jacobi iteration method

Time:12-02

I'm trying to write a programm that solves system of equations Ax=B using Gauss-Jacobi iteration method.

#include <math.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    double **a, *b, *x, *f, eps = 1.e-2, c;  
    int n = 3, m = 3, i, j, bool = 1, d = 3;
    /* printf("n=") ; scanf("%d", &n);
       printf("m=") ; scanf("%d", &n) */
   
   
    a =malloc(n * sizeof *a);
    for (i = 0; i < n; i  ) 
        a[i] = (double*)malloc(m * sizeof(double));

    b = malloc(m * sizeof *b);
    x = malloc(m * sizeof *x) ;  
    f = malloc(m * sizeof *f) ;
    for (i = 0; i < n; i  ) {
        for (j = 0; j < m; j  ) { 
            printf("a[%d][%d]=", i, j); 
            scanf("%le", &a[i][j]); 
            if(fabs(a[i][i])<1.e-10) return 0 ; 
        }

        printf("\n") ;
    }
        
    printf("\n") ;
        
    for (i = 0; i < n; i  ) {
        for (j = 0; j < m; j  ) { 
            printf("a[%d][%d]=%le  ", i, j, a[i][j]); 
        }
         
        printf("\n") ;
    }
    
    for (j = 0; j < m; j  ) { 
        printf("x[%d]=", j); 
        scanf("%le", &x[j]); 
    } //intial guess
    
    printf("\n") ;
    
    for (j = 0; j < m; j  ) { 
        printf("b[%d]=", j); 
        scanf("%le", &b[j]); 
    }
    
    printf("\n")  ;

    while (1) {
        bool = 0;
        for (i = 0; i < n; i  ) {
            c = 0.0;
            for (j = 0; j < m; j  ) 
                if (j != i) 
                    c  = a[i][j] * x[j];  
            f[i] = (b[i] - c) / a[i][i];
        }
       
        for (i = 0; i < m; i  )  
            if (fabs(f[i] - x[i]) > eps) 
                bool = 1;
       
        if (bool == 1) 
            for (i = 0; i < m; i  ) 
                x[i] = f[i];
        else if (bool == 0) 
            break;
    }

    for (j = 0; j < m; j  ) 
        printf("%le\n", f[j]);

    return 0;
}

The condition of stoping the loop is that previous approximation minus current approximation for all x is less than epsilon. It seems like i did everything according to algorithm,but the programm doesn't work. Where did i make a mistake?

CodePudding user response:

While not the most strict condition, the usual condition requiered to guarantee convergence in the Jacobi and Gauss-Seidel methods is diagonal dominance,

abs(a[i][i]) > sum( abs(a[i][j]), j=0...n-1, j!=i)

This test is also easy to implement as a check to run before the iteration.

The larger the relative gap in all these inequalities, the faster the convergence of the method.

  • Related