[c++] 幂法求特征向量
2024-10-06 23:08:49
幂法的原理可参考此篇论文: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; }
部分参数可修改用于扩展
最新文章
- [LeetCode] Can I Win 我能赢吗
- int与CString互相转化
- The communication of Linux Server and Localtion
- maven使用
- java 代码的细节优化
- C++开源代码覆盖率工具OpenCppCoverage介绍(Windows)
- python 任意新闻正文提取
- 面向过程部分 Java 和 C++ 的区别
- PHP学习笔记-00
- Optimal Milking
- vijosP1471 教主的游乐场
- PS:改装店收的是友情价,包安装十五个毛主席。
- MySQL与mabits大小比较、日期比较示例
- 【配置】电信华为HG8245 无线路由器配置 有贴图
- C++不支持Unicode,即使utf8
- poj 3268 最短路dijkstra *
- Leetcode刷题记录:计算复数乘法
- java对象内存占用
- UniGUI的TUniLoginForm窗口自定义背景色
- EJB3 jpa 数据库表的映射关系