c11.cpp
资源名称:数值分析课程设计.zip [点击查看]
上传用户:zhdd911129
上传日期:2007-05-11
资源大小:722k
文件大小:2k
源码类别:
matlab例程
开发平台:
Matlab
- //C11.cpp
- //Find the greatest eigenvaue,using Power Methom
- #include <iostream.h>
- #include <math.h>
- #include <time.h>
- const int N=3;
- double maxval(double x[],int n)
- {
- double max;
- int i;
- max=fabs(x[0]);
- for(i=1;i<n;i++)
- {
- if(fabs(x[i])>max)
- max=fabs(x[i]);
- }
- return max;
- }
- void PowerMethom(double a[][N],double z0[],double tol,int maxtimes,int n)
- {
- int i,j,k;
- double max,maxlast;
- double y[N],z[N];
- for (i=0;i<n;i++)
- {
- z[i]=z0[i];
- }
- for(k=1;k<=maxtimes;k++)
- {
- for (i=0;i<n;i++)
- {
- y[i]=0;
- }
- //Matrix Mutiply
- for (i=0;i<n;i++)
- {
- for (j=0;j<n;j++)
- {
- y[i]+=a[i][j]*z[j];
- }
- }
- if (k>1)
- {
- maxlast=max;
- }
- max=maxval(y,n);
- if (k>1 && fabs(maxlast-max)<tol)
- {
- cout<<"Success,iterate "<<k<<" times"<<endl;
- cout<<"Eigenvaule: "<<max<<endl;
- cout<<"The eigenvextor is: (";
- for (i=0;i<n;i++)
- {
- cout<<z[i];
- if (i<n-1)
- cout<<",";
- else
- cout<<")"<<endl;
- }
- return;
- }
- for (i=0;i<n;i++)
- {
- z[i]=y[i]/max;
- }
- }
- }
- void main()
- {
- double a[][N]={2,4,6,3,9,15,4,16,36};
- double z[N]={1,1,1};
- double tol=1e-5;
- int maxtimes=100;
- clock_t start, finish;
- start = clock(); // Gets system time
- PowerMethom(a,z,tol,maxtimes,N);
- finish = clock(); // Gets system time again
- cout<<"The methom takes time: "<<(double)(finish - start) / CLOCKS_PER_SEC<<endl;
- cin>>tol;
- }
- //迭代7次,精度<1e-5, 特征值:43.88,特征向量:(0.185868,0.446232,1) ,耗时0.01秒
- //算法基本让人满意,但耗时偏多