Created
February 19, 2019 08:51
-
-
Save karngyan/225d4b9929016947b0601317124374e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
#include<stdbool.h> | |
#define N 110 | |
double old_x[N]; | |
double new_x[N]; | |
double a[N][N]; | |
double b[N]; | |
double e = 0.0001; | |
double cal_new_x(int i, int n) | |
{ | |
int j; | |
double res = b[i]; | |
for(j = 1 ; j<=n; ++j) | |
{ | |
if(i!=j) | |
res -= a[i][j]*old_x[j]; | |
} | |
return res/a[i][i]; | |
} | |
bool check(int n) | |
{ | |
int i ,j; | |
for(i = 1 ; i<=n ; ++i) | |
{ | |
if(fabs(old_x[i] - new_x[i]) > e) | |
return false; | |
} | |
return true; | |
} | |
int solve(int n) | |
{ | |
int i,j; | |
int k = 0; | |
while(1) | |
{ | |
k++; | |
for(i = 1 ; i<=n ; ++i) | |
{ | |
new_x[i] = cal_new_x(i,n); | |
} | |
if(check(n)) | |
return k; | |
for(i = 1; i<=n ; ++i) | |
old_x[i] = new_x[i]; | |
} | |
return -1; | |
} | |
signed main() | |
{ | |
int i , j , p , q , n; | |
printf("\t--GAUSS JACOBI ITERATIVE METHOD--\n\n"); | |
printf("Enter number of unknowns: "); | |
scanf("%d", &n); | |
printf("Enter the augmented matrix: \n"); | |
for(i = 1 ; i<=n ; ++i) | |
{ | |
for(j = 1 ; j<=n ; ++j) | |
{ | |
scanf("%lf" , &a[i][j]); | |
} | |
scanf("%lf" , &b[i]); | |
} | |
for(i = 1 ; i<=n ; ++i) | |
old_x[i] = 0; | |
int k = solve(n); | |
printf("\n"); | |
for(i = 1 ; i<=n ; ++i) | |
{ | |
printf("x%d = %.4lf\n", i , new_x[i]); | |
} | |
printf("\nTotal Iteration(k) = %d\n\n", k); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment