How can I get the roots of a polynomial with coefficients in C++ using Eigen library?
In Python:
>>> import numpy as np
>>> coeff = [0.708563939215852, -0.3111717537041549, -0.2151830138973625]
>>> np.roots(coeff)
array([ 0.81279407, -0.37363574])
In Matlab:
>> coeff = [0.708563939215852, -0.3111717537041549, -0.2151830138973625]
>> roots(coeff)
ans =
0.812794068532020
-0.373635742116877
I tried in C++ with Eigen Library but receive a different result:
#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}}
Thanks to the comment of @rafix07, following code gives me the same result as in NumPy and MATLAB. The order of the coefficients have to be swaped.
#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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With