Find Roots Of A Quadratic Equation in Java

Exercise:

Write a Java Program to find all the roots of a quadratic equation.

Click Here to View the Solution!
public class QuadraticRoots {
 
    public static void main(String[] args) {
 
        double a = 3.1, b = 11, c = 4.1;
        double root1, root2;
 
        double determinant = b * b – (4 * a * c);
 
        //checking condition for real and different roots
        if(determinant > 0) {
            root1 = (-b + Math.sqrt(determinant)) / (2 * a);
            root2 = (-b - Math.sqrt(determinant)) / (2 * a);
 
     System.out.format("root1 = %.2f and root2 = %.2f", root1 , root2);
        }
        // Checking condition for real and equal roots
        else if(determinant == 0) {
            root1 = root2 = -b / (2 * a);
 
            System.out.format("root1 = root2 = %.2f;", root1);
        }
        // If roots are imaginary (not real)
        else {
            double realPart = -b / (2 *a);
            double imaginaryPart = Math.sqrt(-determinant) / (2 * a);
 
            System.out.format("root1 = %.2f+%.2fi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart, imaginaryPart);
        }
    }
} 
Click Here to View the Output!
root1 = -0.42 and root2 = -3.13
aClick Here to View the Explanation!
  • This program is used for finding out all roots in a quadratic equation and also printing the roots by using the method format() provided by Java. This is done through the if…else statement and a Java library Math.sqrt().
  • In the quadratic equation ax^2 + bx + c = 0, the value of the coefficients a, b and c are initially set in the program as 3.1, 11 and 4.1.
  • The determinant of the quadratic equation is specified in the program , which is calculated by using the values stated in the program. The value of the determinant will determine the nature and value of the roots. The condition for the different types of roots is as following
    • If the value of the determinant will be greater than 0, then the roots will be real and different.
    • If the value of the determinant will be equal to 0, then the roots will be real and equal.
    • If the value of the determinant will be less than 0, then the roots will not be real.
  • It is to be noted that the library Math.sqrt is used for calculating the square root in the quadratic equations.
  • All the calculated roots are printed through the format() method in Java. However, printf() can also be used.

%d bloggers like this: