Skip to content

Instantly share code, notes, and snippets.

@karngyan
Created February 19, 2019 08:52
Show Gist options
  • Save karngyan/af8ba2ee5a025f0031e51d1cd0cbd377 to your computer and use it in GitHub Desktop.
Save karngyan/af8ba2ee5a025f0031e51d1cd0cbd377 to your computer and use it in GitHub Desktop.
#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(j<i)
res -= a[i][j]*new_x[j];
if(j>i)
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 SEIDEL 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]);
}
int k = 0;
for(i = 1 ; i<=n ; ++i)
old_x[i] = 0;
int total_iteration = 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", total_iteration);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment