Επίλυση δευτεροβάθμιας εξίσωσης

import gr.aueb.dds.BIO;

/*
 * Solve a qudratic equation ax^2 + bx + c = 0
 * Demonstrates the use of math calculations, functions, case analysis
 */
class Quadratic {
        public static void main(String args[]) {
                double a, b, c;         // Equation factors
                double d;               // Discriminant

                BIO.print("a=");
                a = BIO.readDouble();
                BIO.print("b=");
                b = BIO.readDouble();
                BIO.print("c=");
                c = BIO.readDouble();

                if (a == 0) {
                        if (b == 0) {
                                BIO.println("No solutions");
                        } else {
                                // Not really quadratic; one root
                                BIO.print("r=");
                                BIO.println(-c / b);
                        }
                } else {
                        // One complex, one, or two roots
                        d = b * b - 4 * a * c;
                        if (d < 0) {
                                // Complex root
                                BIO.print("r=");
                                // Real part
                                BIO.print(-b / 2 / a);
                                BIO.print("+");
                                // Imaginary part
                                BIO.print(Math.sqrt(-d) / 2 / a);
                                BIO.println("i");
                        } else if (d == 0) {
                                // Two equal roots
                                BIO.print("r1=r2=");
                                BIO.println(-b / 2 / a);
                        } else {
                                // Two different real roots
                                BIO.print("r1=");
                                BIO.println((-b + Math.sqrt(d)) / 2 / a);
                                BIO.print("r2=");
                                BIO.println((-b - Math.sqrt(d)) / 2 / a);
                        }
                }
        }
}

Σημείωση

Στην πράξη ο παραπάνω κώδικας είναι αριθμητικά ασταθής. Για να λύσουμε τη δευτεροβάθμια εξίσωση:
a x2 + b x + c = 0
αν η τιμή του a ή του c ή και των δύο είναι πολύ μικρή τότε μια από τις ρίζες περιλαμβάνει την αφαίρεση δύο σχεδόν ίσων αριθμών (του β και της διακρίνουσας) και το αποτέλεσμα δε θα είναι ακριβές. Για το λόγο αυτό υπολογίζουμε τις δύο ρίζες ως εξής:
double sign , q;

if (b < 0) {
        sign = -1.0;
else {
        sign = 1.0;
}
q = -(b + sign * d) / 2.0;
x1 = q / a;
x2 = c / q;