GAUSS JACOBI METHOD
July 22, 2022
Solve The Given Linear Equations Systems By Using Gauss Jacobi Method
Source code of C program:-
#include <stdio.h>#include <math.h>int main(){ int i, j, k, n, d, flag = 0, iteration = 0; float a[20][20], x[20], y[20], err, s; printf("Enter the number of equations: "); scanf("%d", &n); printf("\nEnter the correction upto decimal place: "); scanf("%d", &d); err = (5.0 / pow(10, d)); printf("\nEnter co-efficient matrix [A] row wise:\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("\na[%d][%d]= ", i + 1, j + 1); scanf("%f", &a[i][j]); } printf("\n"); } printf("\n\nEnter column matrix [B] row wise:\n"); for (i = 0, j = n; i < n; i++) { printf("\nb[%d]= ", i + 1); scanf("%f", &a[i][j]); } // Diagonaly dominant checking. for (i = 0; i < n; i++) { s = 0.0; for (j = 0; j < n; j++) { if (i == j) continue; s = s + (fabs(a[i][j])); } if ((fabs(a[i][i])) < s) { printf("\nThe entered system of linear equeation is not diagonaly dominant.\n"); return 1; } } for (i = 0; i < n; i++) { x[i] = 0.0; y[i] = 0.0; } do { iteration++; printf("\n\nIteration: %d\n\n", iteration); for (i = 0; i < n; i++) { x[i] = a[i][n]; for (j = 0; j < n; j++) { if (i == j) continue; x[i] = x[i] - a[i][j] * y[j]; } x[i] = x[i] / a[i][i]; } for (i = 0; i < n; i++) { flag = 0; if ((fabs(x[i] - y[i])) > err) { flag = 1; for (j = 0; j < n; j++) { y[j] = x[j]; } break; } } for (j = 0; j < n; j++) { printf("x[%d]=%f\t", j + 1, x[j]); } } while (flag == 1); printf("\n\nThe solution is:\n"); for (i = 0; i < n; i++) { printf("x[%d]=%f\n", i + 1, x[i]); } return 1;}
Input-Output :-
abhi@hp-15q-laptop:~$ gcc gauss_jacobi.c abhi@hp-15q-laptop:~$ ./a.out
Enter the number of equations: 3
Enter the correction upto decimal place: 5
Enter co-efficient matrix [A] row wise:
a[1][1]= 4
a[1][2]= -1
a[1][3]= -1
a[2][1]= -2
a[2][2]= 6
a[2][3]= 1
a[3][1]= -1
a[3][2]= 1
a[3][3]= 7
Enter column matrix [B] row wise:
b[1]= 3
b[2]= 9
b[3]= -6
Iteration: 1
x[1]=0.750000 x[2]=1.500000 x[3]=-0.857143
Iteration: 2
x[1]=0.910714 x[2]=1.892857 x[3]=-0.964286
Iteration: 3
x[1]=0.982143 x[2]=1.964286 x[3]=-0.997449
Iteration: 4
x[1]=0.991709 x[2]=1.993622 x[3]=-0.997449
Iteration: 5
x[1]=0.999043 x[2]=1.996811 x[3]=-1.000273
Iteration: 6
x[1]=0.999135 x[2]=1.999727 x[3]=-0.999681
Iteration: 7
x[1]=1.000011 x[2]=1.999658 x[3]=-1.000085
Iteration: 8
x[1]=0.999893 x[2]=2.000018 x[3]=-0.999950
Iteration: 9
x[1]=1.000017 x[2]=1.999956 x[3]=-1.000018
Iteration: 10
x[1]=0.999985 x[2]=2.000009 x[3]=-0.999991
Iteration: 11
x[1]=1.000004 x[2]=1.999993 x[3]=-1.000003
The solution is:
x[1]=1.000004
x[2]=1.999993
x[3]=-1.000003