这类数值库多项式求根的有很多开源实现,常见的boost::math cgal occ vtk eigen3甚至有些3d库中也有,有些是模板库,这个是rl库中的求实根例子。
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <rl/math/Polynomial.h>
int main(int argc, char** argv)
{
if (argc < 2)
{
std::cout << "Usage: rlPolynomialRootsDemo C0 ... CN" << std::endl;
return EXIT_FAILURE;
}
std::vector<rl::math::Real> c(argc - 1);
for (std::size_t i = 0; i < c.size(); ++i)
{
c[i] = boost::lexical_cast<rl::math::Real>(argv[i + 1]);
std::cout << (i > 0 ? " + " : "") << c[i] << " * x^" << i;
}
std::cout << " = 0" << std::endl;
std::vector<rl::math::Real> roots = rl::math::Polynomial<rl::math::Real>::realRoots(c);
std::cout << roots.size() << " solution" << (roots.size() != 1 ? "(s)" : "") << std::endl;
for (std::size_t i = 0; i < roots.size(); ++i)
{
std::cout << "x[" << i << "] = " << roots[i] << std::endl;
}
return EXIT_SUCCESS;
}