public class Power_method
{
// to approximate the dominant eigenvalue and associated eigenvector of the
// nxn matrix with a given non-zero vector x

//  Numerical Analysis -- Richard L. Burden -- J.Douglas Faires
//  Page 562  9th edition
	
double A[][]; 
double x[];
double mu;
int N;

     public Power_method(double AA[][],double xx[],int NN)
     {
	 A=AA;    
	 x=xx;   
	 N=NN;
	 }

	  public static double[] multiply(double[][] left,double[] right)
      {
         //multiplication of one matrix with one vector
          int ii,jj,i,j,k;
          int m1=left[0].length;
          int n1=left.length;
          int m2=right.length;
          double[] b;
          b=new double[m2];
          if(n1 != m2)
          {
             System.out.println("inner matrix dimensions must agree");
             for(ii=0;ii<n1;ii++)
             {
               b[ii]=0;
             }
             return b;
          }
             for(i=0;i<m1;i++)
             {
                b[i]=0;
                for(k=0;k<n1;k++)
	            b[i]+=left[i][k]*right[k];
             }
             return b;
             //end of multiply of a matrix and a vector
       }
	 
	 
     public  double norminf(double v[])
    {
     //infinite vector norm
    double x;
    double max=0;
    for(int i=0;i<v.length;i++)
      {
      x=Math.abs(v[i]);
      if(x>max) max=x;
      }
    return max;
    }
	 
	 
	 public  double[][] eigenvalue_and_eigenvector()
	 {
	 int k=1;
	 double mu0=0;
	 double mu1=0;
	 int n=A.length;
	 double y[]=new double[n];
	 double muu;
	 	 
	      while(k<N)
	      {
		      y=multiply(A,x);
		      mu=y[0];
		      muu=mu0-(((mu1-mu0)*(mu1-mu0))/(mu-2*mu1+mu0));
		      for(int i=0;i<n;i++)
		      {x[i]=y[i]/y[0];}
		      if(y[0]==0)
		      {break;}
		      k++;
	          mu0=mu1;	      
		      mu1=muu;
		  }
		 double depo[][]=new double[2][n];
		 for(int i=0;i<n;i++)
		 {depo[0][i]=x[i];} 
		 depo[1][0]=mu;
	  
		 return depo;
		 
	}
	 
	 public static void main(String args[])
	 {
		 double A[][]={{-4,14,0},{-5,13,0},{-1,0,2}};
		 double x[]={1,1,1};
		 int N=50;//number of iteration;
	     Power_method Pm=new Power_method(A,x,N);	 
		 double yy[][]=Pm.eigenvalue_and_eigenvector();
		 int n=A.length;
		 double eigenvec[]=new double[n];
		 for(int i=0;i<n;i++)
		 {eigenvec[i]=yy[0][i];}
		 System.out.println("Maximum eigenvalue = "+yy[1][0]);
		 System.out.println("Eigenvector for maximum eigenvalue");
		 for(int i=0;i<n;i++)
		 System.out.println((eigenvec[i]));
	 }









}