Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating roots of polynom in C++ with Eigen library

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}}
like image 993
bladan Avatar asked Nov 04 '25 07:11

bladan


1 Answers

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();
like image 145
bladan Avatar answered Nov 05 '25 23:11

bladan