参考别人的博客,顺便借鉴过来作个笔记.
一.使用多项式的伴随矩阵进行求解
多项式:
多项式的伴随矩阵:
的特征值就是的根.
其中是个方阵,是个列向量,是个常量,其中是矩阵的特征向量,是矩阵的特征值.
使用Eigen进行多项式的求解:
#include <iostream>
#include <Eigen/Core>
// 稠密矩阵的代数运算(逆,特征值等)
#include <Eigen/Dense>
using namespace std;
int main( int argc, char** argv )
{
Eigen::Matrix<double, 4, 4> matrix_44;
//复数动态矩阵
//P(x) = x^4 + 2*x^3 +3*x^2 +4*x + 5;
Eigen::Matrix<complex<double>, Eigen::Dynamic, Eigen::Dynamic> matrix_eigenvalues;
//同样测试 12345
matrix_44 << 0, 0, 0, -5,
1, 0, 0, -4,
0, 1, 0, -3,
0, 0, 1, -2;
std::cout<<"matrix_44: "<<std::endl<<matrix_44<<std::endl<<std::endl;
matrix_eigenvalues = matrix_44.eigenvalues();
//std::cout<<"matrix_44.eigenvalues: "<<std::endl<<matrix_44.eigenvalues()<<std::endl;
std::cout<<"matrix_eigenvalues: "<<std::endl<<matrix_eigenvalues<<std::endl;
return 0;
}
或者使用Eigen多项式
#include<iostream>
#include <Eigen/Eigen>
#include <unsupported/Eigen/Polynomials>
using namespace std;
int main()
{
Eigen::PolynomialSolver<double,Eigen::Dynamic> solver; //多项式求根
Eigen::VectorXd coeff(5);
coeff[0] = 5;
coeff[1] = 4;
coeff[2] = 3;
coeff[3] = 2;
coeff[4] = 1;
solver.compute(coeff); //compute()计算多项式复数根
const Eigen::PolynomialSolver<double,Eigen::Dynamic>::RootsType& r = solver.roots(); //roots()返回多项式复数根
std::vector<double> real_root;
for (int i = 0; i< r.rows();++i)
{
if (r[i].imag() != 0.0)
{
continue;
}
real_root.push_back(r[i].real());
}
for(int i=0;i<real_root.size();++i)
{
cout<<"多项式方程的实根:"<<real_root[i]<<std::endl;
}
return 0;
}
参看链接: