使用 Eigen 库在 C++ 中计算多项式的根

Calculating roots of polynom in C++ with Eigen library

如何使用 Eigen 库在 C++ 中获取带系数的多项式的根?

在Python中:

>>> import numpy as np
>>> coeff = [0.708563939215852, -0.3111717537041549, -0.2151830138973625]
>>> np.roots(coeff)
array([ 0.81279407, -0.37363574])

在 Matlab 中:

>> coeff = [0.708563939215852, -0.3111717537041549, -0.2151830138973625]
>> roots(coeff)
ans = 
   0.812794068532020
   -0.373635742116877

我在 C++ 中尝试使用 Eigen 库,但收到不同的结果:

#include <unsupported/Eigen/Polynomials>

Eigen::Vector3d coeff(0.708563939215852, -0.3111717537041549, -0.2151830138973625);
Eigen::PolynomialSolver<double, Eigen::Dynamic> solver;
solver.compute(coeff);
const Eigen::PolynomialSolver<double, Eigen::Dynamic>::RootsType &r = solver.roots();

--> r[2] = {{1.2303239390096565, 0.000}, {-2.6764034787849331, 0.000}}

感谢@rafix07 的评论,下面的代码给出了与 NumPy 和 MATLAB 中相同的结果。必须交换系数的顺序。

#include <unsupported/Eigen/Polynomials>

Eigen::Vector3d coeff(-0.2151830138973625, -0.3111717537041549, 0.708563939215852);
Eigen::PolynomialSolver<double, Eigen::Dynamic> solver;
solver.compute(coeff);
const Eigen::PolynomialSolver<double, Eigen::Dynamic>::RootsType &r = solver.roots();