import java.io.*;

class NA21
{ 
  public static double [] gauss_seidel(double a[][],double b[])
  {
  double lambda=1.2;
  int n=a.length;
  //starting x vector is zero
  double x[]=new double[n];
  return gauss_seidel(a,b,x,lambda);
  }
  
  public static double [] gauss_seidel(double a[][],double b[],double x[])
  {
  double lambda=1.2;
  int n=a.length;
  return gauss_seidel(a,b,x,lambda);
  }
  	 
  public static double [] gauss_seidel(double a[][],double b[],double x[],double lambda)
  {
  //lambda is the relaxation coefficient  
  int n=a.length;
  int imax=500;//maximum number of iterations 
  double es=1.0e-20;
  double dummy=0;
  double ea=1e-1;
  double sum=0;
  double old=0;
  int iter=0;
  int sentinel=0;
  System.out.print("iter = "+(iter+1)+" ");
  for(int i=0;i<n;i++)
  {  dummy=a[i][i];
     for(int j=0;j<n;j++)
       {a[i][j]/=dummy;}
     b[i]/=dummy;
  }
  for(int i=0;i<n;i++)
  {  sum=b[i];
     for(int j=0;j<n;j++)
       {if(i!=j)sum-=a[i][j]*x[j];}
     x[i]=sum;
     System.out.print(x[i]+ "  ");  
  }
   System.out.println();  
  iter++;
  do
  {
  sentinel=1;
  System.out.print("iter = "+(iter+1)+" ");  
  for(int i=0;i<n;i++)
     { 
	 old=x[i];
	 sum=b[i];
	 for(int j=0;j<n;j++)
	    {if(i!=j) sum-=a[i][j]*x[j];}
	    x[i]=lambda*sum+(1.0-lambda)*old;
	    if(sentinel==1 && x[i]!=0.0 ) {ea=Math.abs((x[i]-old)/x[i])*100.0;}
	    if(ea<es) sentinel=0;
	  System.out.print(x[i]+ "  ");     
     }
  System.out.println();  
  iter++;
  }while(sentinel==1 && iter<imax);  
  if(iter>=imax) System.out.println("Maximum number of iteration is exceed, result might not be valid iter = "+iter);
  return x;
  }
    
  public static void main(String args[]) throws IOException
  {
  double a[][]={{3,-0.1,-0.2},{0.1,7,0.3},{0.3,-0.2,10}};
  double b[]={7.85,-19.3,71.4};


  double x[]={0,0,0};
  double lambda=0.0;
  Text.print(gauss_seidel(a,b),"iterative relaxation  method");
  }
}