[c++] 幂法求特征向量
幂法的原理可参考此篇论文:http://d.wanfangdata.com.cn/Periodical/hnnydxxb2001Z1023
本文求解的是 3 阶矩阵最大特征值及其特征向量
下面是其 C++ 实现代码:
#include <iostream> #include<stdio.h> #include<stdlib.h> #include<math.h> #include<iomanip> using namespace std; double A[3][3]; double Y[3]={1,1,1}; double X[3]={0,0,0}; int row=0; int col=0; double max1=0; void open_file() { FILE *fp; fp = fopen("array.txt", "r"); //3*3矩阵由外部读入 if(fp==NULL) cout<<"File opened failed!"<<endl; for(row=0;row<3;row++) { for(col= 0; col < 3; col ++) fscanf(fp, "%lf,",&A[row][col]); if(feof(fp)) break; } fclose(fp); } void mult() { X[0]=0;X[1]=0;X[2]=0; for(row=0;row<3;row++) { for(col=0;col<3;col++) X[row] +=A[row][col]*Y[col]; } } void to1() { long double tmp=fabs(X[0]); for(int i=1;i<3;i++) { if(fabs(X[i])>tmp) tmp=fabs(X[i]); } for(int i=0;i<3;i++) { Y[i]=X[i]/tmp; } max1=tmp; } int main() { cout <<setiosflags(ios::fixed); open_file(); double ago=max1+100.0; double feature_vector[3]; int k=1; while(fabs(max1-ago)>0.000001) { ago=max1; for(int j=0;j<3;j++) { feature_vector[j]=Y[j]; } mult(); to1(); cout<<"k= "<<k<<" "; for(int i=0;i<3;i++) cout<<X[i]<<" "; cout<<endl; k++; } cout<<endl<<"totally run "<<k-1<<" times"<<endl; cout<<endl<<"the matrix eigenvalue is "<<max1<<endl; cout<<endl<<"the feature vector is "<<"["<<feature_vector[0]<<" , "<<feature_vector[1]<<" , "<<feature_vector[2]<<"]"<<endl; }
部分参数可修改用于扩展