Hi i want to solve 6 equations with 6 unknowns using gauss siedel method in c. i wrote a code in c and solved for 3 equations and 3 unknowns:
#include <stdio.h>
int main(void)
{
int i,j,n,iter,sentinel;
float dummy,sum,old,lambda,ea,es;
float a[3][3]= {{3,(-0.1),(-0.2)},{0.1,7,(-0.3)},{0.3,(-0.2),10}};
float b[3]={7.85,-19.3,71.4};
float x[3]={0,0,0};
es=0.001;
lambda=1.0001;
n=2;
for(i=0;i<=n;i++){
dummy=a[i][i];
for(j=0;j<=n;j++){
a[i][j]=a[i][j]/dummy;
}
b[i]=b[i]/dummy;
}
for(i=0;i<=n;i++){
sum=b[i];
for(j=0;j<=n;j++){
if(i!=j){
sum=sum-a[i][j]*x[i];
}
}
x[i]=sum;
}
iter=1;
while(1){
sentinel=1;
for(i=0;i<=n;i++){
old=x[i];
sum=b[i];
for(j=0;j<=n;j++){
if (i!=j) {sum=sum-a[i][j]*x[j];}
}
x[i]=lambda*sum+(1-lambda)*old;
if (sentinel=1 && x[i]!=0){
ea=((x[i]-old)/x[i])*100;
if (ea<0) {ea=-ea;}
if (ea>es) {sentinel=0;}
}
}
iter=iter+1;
if (sentinel=1){break;}
}
printf("%f\n%f\n%f\n",x[0],x[1],x[2]);
getch();
return 0;
}
However i cant solve 6 ones using this code:
#include <stdio.h>
int main(void)
{
int i,j,n,iter,sentinel;
float dummy,sum,old,lambda,ea,es;
float a[6][6]= {{0.866,0,(-0.5),0,0,0},{0.5,0,0.866,0,0,0},{(-0.866),(-1),0,(-1),0,0},{(-0.5),0,0,0,(-1),0},{0,1,0.5,0,0,0},{0,0,(-0.866),0,0,(-1)}};
float b[6]={0,(-1000),0,0,0,0};
float x[6]={0,0,0,0,0,0};
es=0.001;
lambda=1.0001;
n=5;
for(i=0;i<=n;i++){
dummy=a[i][i];
for(j=0;j<=n;j++){
a[i][j]=a[i][j]/dummy;
}
b[i]=b[i]/dummy;
}
for(i=0;i<=n;i++){
sum=b[i];
for(j=0;j<=n;j++){
if(i!=j){
sum=sum-a[i][j]*x[i];
}
}
x[i]=sum;
}
iter=1;
while(1){
sentinel=1;
for(i=0;i<=n;i++){
old=x[i];
sum=b[i];
for(j=0;j<=n;j++){
if (i!=j) {sum=sum-a[i][j]*x[j];}
}
x[i]=lambda*sum+(1-lambda)*old;
if (sentinel=1 && x[i]!=0){
ea=((x[i]-old)/x[i])*100;
if (ea<0) {ea=-ea;}
if (ea>es) {sentinel=0;}
}
}
iter=iter+1;
if (sentinel=1){break;}
}
printf("%f\n%f\n%f\n",x[0],x[1],x[2]);
getch();
return 0;
}
If you find my error i will be very happy. Thank you
Try one:
_Before starting reorder the rows so it couldn't be any 0 in the diagonal.
_If the element is zero, jitter it a little.
_Say that you can't solve it.