POWER METHOD

/*

1. Start
2. Get the values of a,x aerr, maxtir
3. Define Subroutine findmax

4. Call function findmax with e, x, n

5. Loop for itr = 1 to maxtir

6. Calculate r = a*x

7. Call function findmax with t, r, n

8. normalise  r

9. maxe = 0;

10. Loop for i = 0 to N-1

11. err = fabs(x[i] - r[i])

12. Is err>maxe, if yes maxe = err otherwise proceed

13. x[i] = r[i]

14. End Loop (i)

15. errv = fabs(t-e)

16. e = t

17. Print results of Iteration

18. Is errv < aerr  && maxe < aerr, if Yes Print Solution and STOP otherwise proceed

19. End Loop (itr)

20. Print Solution does not converge

21. Stop


Algorithm for findmax function

 

1. max = fabs(x(1))

2. Loop for i = 1 to N-1

3. Is fabs (x[i] > max?, If yes proceed otherwise go to step 5

4. max = fabs(x[i])

5. End loop (i)

6. Stop

*/ 



/* Power method for finding largest eigenvalue */

#include <stdio.h>

#include <math.h>

 

#define SIZE 3

typedef float array[SIZE];

 

void findmax(float *max,array x){

int i;

*max = fabs(x[0]);

  for (i=1; i<SIZE; i++)

if (fabs(x[i]) > *max)

*max = fabs(x[i]);

 }

main(){

float a[SIZE][SIZE],x[SIZE],r[SIZE],maxe, err,errv,aerr,e,s,t;

int i,j,k,itr,maxitr;

printf("Enter the matrix rowwise\n");

for (i=0; i<SIZE; i++)

    for (j=0; j<SIZE; j++)

        scanf("%f",&a[i][j]);

printf("Enter the initial approximation" "to the eigen vector\n");

for (i=0;i<SIZE;i++)

scanf("%f",&x[i]);

 printf("Enter the allowed error,maximum iterations\n");

 scanf("%f %d",&aerr,&maxitr);

 printf("Itr no. Eigenvalue" "EigenVector\n");

 /* now finding the largest eigenvalue in the initial approx. to eigen vector */

 findmax(&e,x);

 /* now starting the iterations */

for (itr=1;itr<=maxitr;itr++){ /* loop to multiply the matrices a and x */

for (i=0; i<SIZE; i++) {

s = 0;

  for (k=0; k<SIZE; k++)

s += a[i][k]*x[k];

  r[i]=s;

 }

findmax(&t,r);

 for (i=0; i < SIZE; i++)

r[i] /= t;

 maxe = 0;

 for (i=0;i<SIZE;i++){

err = fabs(x[i]-r[i]);

if (err > maxe) maxe = err;

 x[i] = r[i];

 }

errv = fabs(t-e);

e = t;

printf("%4d %12.4f",itr,e);

 for (i=0; i<SIZE; i++)

printf("%9.3f",x[i]);

 printf("\n");

 if ((errv <= aerr) && (maxe <= aerr)){

printf("Converges in %d" "iterations\n",itr);

printf("Largest eigen value" "= %6.2f\n",e);

      printf("Eigenvector:-\n");

   for (i=0;i<SIZE;i++)

printf("x[%3d] = %6.2f\n", i+1,x[i]);

 printf("\n");

 return 0;

 } }

printf("Solution does not converge," "iterations not sufficient\n");

return 1;

 }

Comments

Popular posts from this blog

Write a program to find out the FIRST of the Non‐terminals in a grammar.