/* eigen_power.c works sometimes, slow */ /* just finds the largest eigenvalue */ /* given A, guess V = all ones */ /* loop: V2 = A * V */ /* V3 = V2/largest_magnitude_element */ /* stop when |V3-V| small */ /* V = V3 goto loop */ /* */ /* check the eigenvalue and eigenvector */ #include #undef abs #define abs(a) ((a)<0.0?(-(a)):(a)) static double eigenp(int n, double A[n][n], double V[], double *e); static vecprint(int n, double V[]); static matprint(int n, double A[][]); static matmul(int n, double A[n][n], double V[], double V2[]); static double determinant(int n, double A[n][n]); static void inverse(int n, double A[n][n], double AA[n][n]); int main(int argc, char *argv[]) { int i, j, k, n; double e, err, det; double A1[3][3] = {{ 3.0, -1.0, 0.0}, {-2.0, 4.0, -3.0}, { 0.0, -1.0, 1.0}}; double A2[3][3] = {{ 6.0, 12.0, 19.0}, {-9.0, -20.0, -33.0}, { 4.0, 9.0, 15.0}}; double V[3], Vc[3], A[3][3], A3[3][3]; printf("eigen_power.c running, find largest eigenvalue \n"); n = 3; printf("initial matrix A1 n=%d\n", n); matprint(n, A1); err = eigenp(n, A1, V, &e); printf("eigenvalue=%12.8f, error=%g, eigenvector is \n", e, err); vecprint(n, V); printf("check eigenvalue and eigenvector \n"); for(i=0; ibigabs) big=V2[i]; bigabs = abs(big); } for(i=0; i ABS_PIVOT ){ I_PIVOT = i; PIVOT = B[ROW[i]*n+k]; ABS_PIVOT = abs(PIVOT); } } /* HAVE PIVOT, INTERCHANGE ROW POINTERS */ if(I_PIVOT != k){ HOLD = ROW[k]; ROW[k] = ROW[I_PIVOT]; ROW[I_PIVOT] = HOLD; D = - D; } /* CHECK FOR NEAR SINGULAR */ if(ABS_PIVOT < 1.0E-10){ free(B); free(ROW); return 0.0; } else { D = D * PIVOT; /* REDUCE ABOUT PIVOT */ for(j=k+1; j abs_pivot ){ I_pivot = i ; J_pivot = j ; pivot = AA[row[i]][col[j]] ; } } } if(abs(pivot) < 1.0E-10){ free(row); free(col); free(temp); printf("MATRIX is singular !!! \n"); return; } hold = row[k]; row[k]= row[I_pivot]; row[I_pivot] = hold ; hold = col[k]; col[k]= col[J_pivot]; col[J_pivot] = hold ; /* reduce about pivot */ AA[row[k]][col[k]] = 1.0 / pivot ; for (j=0; j