多项式方程求根

  • Post author:
  • Post category:其他

参考别人的博客,顺便借鉴过来作个笔记.

一.使用多项式的伴随矩阵进行求解

多项式:  P(x)=x^{n} + c_{n-1}x^{n-1}+c_{n-2}x^{n-2}+...+c_{1}x+c_{0}

多项式的伴随矩阵:

M_{x} =\begin{bmatrix} 0& 0& ...& 0&-c_{0}\ 1& 0& ...& 0& -c_{1}\ 0& 1& ...& 0& -c_{2}\ 0& 0& ...& ...&... \ 0& 0& ...& 1& -c_{n-1} \end{bmatrix}

的特征值就是P(x)的根.

Ay = \lambda y

其中A是个方阵,y是个列向量,\lambda是个常量,其中y是矩阵A的特征向量,\lambda是矩阵A的特征值.

使用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;
  
}

参看链接:

https://blog.csdn.net/fb_941219/article/details/102984587

http://eigen.tuxfamily.org/dox-devel/unsupported/classEigen_1_1PolynomialSolverBase.html#a07bcd5339be5eacdf7e566d07d81bedb


版权声明:本文为qq_37611824原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。