CS 1073 Introductory Programming
for Scientific Applications
Quadratic Formula
|
Simple quadratic formula in Java:
Here is a simple Java program that uses the quadratic formula to
calculate roots:
// Quadratic: roots of a quadratic equation
public class Quadratic {
public static void main(String[] args) {
double a, b, c;
a = 1;
b = -2;
c = -3;
double r1, r2;
double d;
d = b*b - 4.0*a*c;
if ( d < 0) {
System.out.println("Imaginary roots");
}
else {
r1 = (-b + Math.sqrt(d))/(2.0*a);
r2 = (-b - Math.sqrt(d))/(2.0*a);
System.out.println("r1: " + r1);
System.out.println("r2: " + r2);
}
}
}
Here are results of a run:
r1: 3.0
r2: -1.0
Change c = -3; to c = 3; and you get:
Imaginary roots
Change a = 1; b = -2; c = -3 to a = 1; b = 4; c = 2 and you get:
r1: -0.5857864376269049
r2: -3.414213562373095