Search in sources :

Example 1 with EigenDecomposition

use of org.hipparchus.linear.EigenDecomposition in project symja_android_library by axkr.

the class Roots method findRoots.

/**
	 * <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
	 */
@Nonnull
public static IAST findRoots(double... coefficients) {
    int N = coefficients.length - 1;
    // Construct the companion matrix
    RealMatrix c = new Array2DRowRealMatrix(N, N);
    double a = coefficients[N];
    for (int i = 0; i < N; i++) {
        c.setEntry(i, N - 1, -coefficients[i] / a);
    }
    for (int i = 1; i < N; i++) {
        c.setEntry(i, i - 1, 1);
    }
    try {
        IAST roots = F.List();
        EigenDecomposition ed = new EigenDecomposition(c);
        double[] realValues = ed.getRealEigenvalues();
        double[] imagValues = ed.getImagEigenvalues();
        for (int i = 0; i < N; i++) {
            roots.append(F.chopExpr(F.complexNum(realValues[i], imagValues[i]), Config.DEFAULT_ROOTS_CHOP_DELTA));
        }
        return roots;
    } catch (Exception ime) {
        throw new WrappedException(ime);
    }
}
Also used : WrappedException(org.matheclipse.core.eval.exception.WrappedException) EigenDecomposition(org.hipparchus.linear.EigenDecomposition) RealMatrix(org.hipparchus.linear.RealMatrix) Array2DRowRealMatrix(org.hipparchus.linear.Array2DRowRealMatrix) Array2DRowRealMatrix(org.hipparchus.linear.Array2DRowRealMatrix) IAST(org.matheclipse.core.interfaces.IAST) WrappedException(org.matheclipse.core.eval.exception.WrappedException) JASConversionException(org.matheclipse.core.eval.exception.JASConversionException) Nonnull(javax.annotation.Nonnull)

Aggregations

Nonnull (javax.annotation.Nonnull)1 Array2DRowRealMatrix (org.hipparchus.linear.Array2DRowRealMatrix)1 EigenDecomposition (org.hipparchus.linear.EigenDecomposition)1 RealMatrix (org.hipparchus.linear.RealMatrix)1 JASConversionException (org.matheclipse.core.eval.exception.JASConversionException)1 WrappedException (org.matheclipse.core.eval.exception.WrappedException)1 IAST (org.matheclipse.core.interfaces.IAST)1