public class Symmetric_power_method
{
//To approximate the dominant eigenvalue and an associated eigenvector 
//of the n × n symmetric matrix A, given a nonzero vector x:	
	
//  Numerical Analysis -- Richard L. Burden -- J.Douglas Faires
//  Page 581 9th edition
double A[][];
double x[];
int N;

     public Symmetric_power_method(double AA[][],double xx[],int NN)
     {
	 A=AA;    
	 x=xx;    
	 N=NN;    
	 }
	 
	 public double multiply(double[] left,double right[])
	 {
	 int n=left.length;
	 double s=0;
	 for(int i=0;i<n;i++)
	 {s+=left[i]*right[i];}	 
	 return s;	 
	 }
	 
	 
	 public  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 norm(double v[],int p)
      {
        //p vector norm
        if(p==0) p=1;
        double total=0;
        double x,y;
        for(int i=0;i<v.length;i++)
        {
         x=Math.abs(v[i]);
         total+=Math.pow(x,p);
        }
        return Math.pow(total,(1.0/p));
      }

      public void eigenvector()
      {
	    int k=1;
	    double p1=norm(x,2);
	    double p2=0;;
	    int n=x.length;
	    double mu=0;;
	    double y[]=new double[n];
	    for(int i=0;i<n;i++) 
	    {x[i]=x[i]/p1;}  
	    
	        while(k<N)
	        {
		    y=multiply(A,x);
		    mu=multiply(x,y);
		    p2=norm(y,2);
		    for(int i=0;i<n;i++)
		    {x[i]=y[i]/p2;}    
		    k++;    
		    }  
		    
	        System.out.println("Maximum eigenvalue of symmetric matrix = "+mu);
	        System.out.println("Eigenvectors of maximum eigenvalue");
	        for(int i=0;i<n;i++)
	        {System.out.println(x[i]);}
	  }

 
	  public static void main(String args[])
      {
	    double A[][]={{4,-1,1},{-1,3,-2},{1,-2,3}};
	    double x[]={1,0,0};
	    int N=80;//number of iteration
	    Symmetric_power_method spm=new Symmetric_power_method(A,x,N);   
	    spm.eigenvector();  
	  }






} 