Returns the negative and positive roots of a quadratic equation a*x^2+b*x+c=0 as a double array. Note that if a<0 then the negative root has the smallest x-value, and if a>0 then the positive root has the smallest x-value. - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Returns the negative and positive roots of a quadratic equation a*x^2+b*x+c=0 as a double array. Note that if a<0 then the negative root has the smallest x-value, and if a>0 then the positive root has the smallest x-value.

Demo Code

/*//from  w  w w.ja v  a2s  . c o  m
 * #%L
 * BlaiseMath
 * --
 * Copyright (C) 2009 - 2016 Elisha Peterson
 * --
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        double a = 2.45678;
        double b = 2.45678;
        double c = 2.45678;
        System.out.println(java.util.Arrays
                .toString(quadraticRoots(a, b, c)));
    }

    /**
     * Returns the negative and positive roots of a quadratic equation a*x^2+b*x+c=0
     * as a double array.<br>
     * Note that if a&lt;0 then the negative root has the smallest x-value, and
     * if a&gt;0 then the positive root has the smallest x-value.
     * @param a coefficient of x^2
     * @param b coefficient of x
     * @param c constant coefficient
     * @return an array [r_neg, r_pos], where r_neg is the negative root and r_pos is the positive root;
     *         an array [NaN, NaN] if the roots are complex;
     *         an array [r] if a=0 so the equation is a line and there is one root r;
     *         null if a=0 and b=0 so that there are no solutions
     */
    public static double[] quadraticRoots(double a, double b, double c) {
        double disc = b * b - 4 * a * c;
        if (disc < -1e-15)
            return new double[] { Double.NaN, Double.NaN };
        else if (a == 0 && b == 0)
            return null;
        else if (a == 0)
            return new double[] { -c / b };
        else
            return new double[] { (-b - Math.sqrt(disc)) / (2 * a),
                    (-b + Math.sqrt(disc)) / (2 * a) };
    }
}

Related Tutorials