代码来源
做法
默认为 有唯一的特征值的情况下,求出主特征值和特征向量
代码中是迭代3次(cnt)
初始向量x,不断左乘矩阵A,不断更新该向量x即可。
主特征值就是 新的x1 除以 旧的x1
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
#define ll long long
#define _for(i, x, n) for(int i = x; i <= n; i++)
void LOOP(float a[20][20], float u[20], int);
float MAX(float u[20], int);
int main()
{
float a[20][20], u[20], x[20],y,z;
int i,j,n;
printf("阶数:");
scanf("%d", &n);
printf("元素值:");
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
scanf("%f", &a[i][j]);
}
}
printf("迭代向量:");
for(i = 0; i < n; i++)
scanf("%f", &u[i]);
y = MAX(u, n);
for(int cnt = 1; cnt <= 3; cnt++)
{
z = y;
LOOP(a, u, n);
y = MAX(u, n);
for(i = 0; i < n; i++)
{
x[i] = u[i] / y;
u[i] = x[i];
}
cout << "过程的特征值" << y << endl;
}
printf("矩阵的特征值:%f\n", y);
printf("矩阵的特征向量:");
for(int i = 0; i < n; i++)
{
printf("%f ", x[i]);
}
return 0;
}
void LOOP(float a[20][20], float u[20], int n)
{
float S, U[20];
int i, j;
for(int i = 0; i < n; i++)
{
U[i] = u[i];
}
for(int i = 0; i < n; i++)
{
S = 0.0;
for(int j = 0; j < n; j++)
{
S = S + a[i][j] * U[j];
}
u[i] = S;
}
}
float MAX(float u[20], int n)
{
float maxi;
int i;
maxi = u[0];
for(i = 0; i < n; i++)
{
if(u[i] > maxi)
{
maxi = u[i];
}
}
return maxi;
}
/*
3
1 -1 0
-2 4 -2
0 -1 1
1 0 0
*/