在 Java 中寻找多项式的根
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13805644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding roots of polynomial in Java
提问by Maciej Piechotka
I need to find (approximate, numerical) solution to Legendre polynomial. I tried the several Java libraries but none have what I am looking for (the closest is commons-math which even has code for finding the solutions in Laguerre Solver but does not expose the method). Is there an existing solution or do I need to implement my own?
我需要找到勒让德多项式的(近似,数值)解。我尝试了几个 Java 库,但没有一个是我想要的(最接近的是 commons-math,它甚至有在 Laguerre Solver 中找到解决方案的代码,但没有公开该方法)。是否有现有的解决方案,还是我需要实施自己的解决方案?
回答by Bhavik Ambani
You can use efficient-java-matrix-library
Please find the below sample example for the same
请在下面找到相同的示例
public class PolynomialRootFinder {
/**
* <p>
* Given a set of polynomial coefficients, compute the roots of the polynomial. Depending on
* the polynomial being considered the roots may contain complex number. When complex numbers are
* present they will come in pairs of complex conjugates.
* </p>
*
* @param coefficients Coefficients of the polynomial.
* @return The roots of the polynomial
*/
public static Complex64F[] findRoots(double... coefficients) {
int N = coefficients.length-1;
// Construct the companion matrix
DenseMatrix64F c = new DenseMatrix64F(N,N);
double a = coefficients[N];
for( int i = 0; i < N; i++ ) {
c.set(i,N-1,-coefficients[i]/a);
}
for( int i = 1; i < N; i++ ) {
c.set(i,i-1,1);
}
// use generalized eigenvalue decomposition to find the roots
EigenDecomposition<DenseMatrix64F> evd = DecompositionFactory.eigGeneral(N, false);
evd.decompose(c);
Complex64F[] roots = new Complex64F[N];
for( int i = 0; i < N; i++ ) {
roots[i] = evd.getEigenvalue(i);
}
return roots;
}
}
回答by T. Neidhart
Since release 3.1, Commons Math supports finding all complex roots of a polynomial function.
自 3.1 版起,Commons Math 支持查找多项式函数的所有复根。
回答by Filip Bláha
commons math has reasonable API for polynomials
公共数学具有合理的多项式 API
// -4 + 3 x + x^2
PolynomialFunction polynomial = new PolynomialFunction(new double[]{ -4, 3, 1});
LaguerreSolver laguerreSolver = new LaguerreSolver();
double root = laguerreSolver.solve(100, polynomial, -100, 100);
System.out.println("root = " + root);