幂法求矩阵最大特征值及其对应的特征向量 C++实现
程序员文章站
2022-04-04 09:46:00
...
#include<iostream>
#include<cstring>
#include<algorithm>
#include<math.h>
#define N 1100
using namespace std;
int n,flag;
float m,next_m,eclipse,sum,A[N][N],z[N],y[N],next_z[N];
void readData();
void power();
void matrixFact();
void Findmax();
void newZ();
void printResult();
float abs(float);
void reckonResidue();
int main()
{
cin>>n;
readData();
power();
return 0;
}
void reckonResidue()
{
float sum=0;
for (int i=1;i<=n;i++)
{
sum+=abs(z[i]-next_z[i]);
}
if (sum<0.001)
{
flag=1;
}
return ;
}
void readData()
{
for (int i=1;i<=n;i++)
{
for (int j=1;j<=n;j++)
{
cin>>A[i][j];
}
}
return ;
}
void power()
{
m=next_m;
flag=0;
eclipse=1e-5;
for (int i=1;i<=n;i++)
{
z[i]=1;
next_z[i]=1;
}
do
{
sum=0;
for (int i=1;i<=n;i++)
z[i]=next_z[i];
matrixFact();
Findmax();
newZ();
reckonResidue();
}while (!flag);
printResult();
return ;
}
void matrixFact()
{
for (int i=1;i<=n;i++)
{
sum=0;
for (int j=1;j<=n;j++)
{
sum+=A[i][j]*z[j];
}
y[i]=sum;
}
for (int i=1;i<=n;i++)
{
cout<<y[i]<<" ";
}
cout<<endl;
return ;
}
void Findmax()
{
m=0;
for (int i=1;i<=n;i++)
{
if (abs(m)<abs(y[i]))
{
m=y[i];
}
}
cout<<"m:"<<m<<endl;
return ;
}
void newZ()
{
for (int i=1;i<=n;i++)
{
next_z[i]=y[i]/m;
}
return ;
}
void printResult()
{
cout<<"矩阵A的最大特征值为:"<<m<<endl;
cout<<"其对应的特征向量为:(";
for (int i=1;i<=n;i++)
{
cout<<next_z[i];
if (i!=n)
{
cout<<",";
}
}
cout<<")"<<endl;
return ;
}
float abs(float cc)
{
return cc>0?cc:-cc;
}
上一篇: HCIA第一天总结
下一篇: xp系统只有32位的么