How to find the roots of a quadratic equation in Java

7 views

```public class MyClass {
static void quadratic_equation_roots(double a, double b, double c) {
double discriminant = (b * b) - (4 * a * c);

double root1, root2;
if (discriminant > 0) {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("root1 = " + root1 + "\nroot2 = " + root2);
}
else if(discriminant == 0) {
root1 = root2 = -b / (2 * a);
System.out.println("root1 = root2 = " + root1);
}
else if(discriminant < 0) {
double real = -b / (2 * a);
double imaginary = Math.sqrt(-discriminant) / (2 * a);
System.out.println("root1 = " + real + "+" + imaginary + "i\nroot2 = " + real + "-" + imaginary + "i");
}
}
public static void main(String args[]) {
double a = 3, b = 5, c = -9;

System.out.println();

a = 3; b = 5; c = 7;
System.out.println();

a = 2; b = 4; c = 2;
}
}

/*
run:

root1 = 1.0887604324451328
root2 = -2.7554270991117993

root1 = -0.8333333333333334+1.2801909579781012i
root2 = -0.8333333333333334-1.2801909579781012i

root1 = root2 = -1.0

*/```