Java Program to Find all Roots of a Quadratic Equation

Write a program to find all roots of a quadratic equation.

To understand this program, you need to have understanding of if else statement and math.sqrt method.

Approach: First of all, you need to know what is quadratic equation. It is an equation which when arranged in equation form returns the result as zero as shown below.

ax2 + bx + c = 0

we can calculate the root of a quadratic equation by using the formula

x = (-b ± √(b2-4ac)) / (2a)

The sign ± indicates that there will be two roots of a number.

root1 = (-b + √(b2-4ac)) / (2a)
root1 = (-b - √(b2-4ac)) / (2a)

The equation b2-4ac is called determinant of a quadratic equation. It denotes the nature of root.

if determinant > 0, roots are real and different
if determinant == 0, roots are real and equal
if determinant < 0, roots are complex complex and different

Here we go with the program

public class RootQuadratic {

    public static void main(String[] args) {

        double a = 2.3, b = 4, c = 5.6;
        double root1, root2;

        double determinant = b * b - 4 * a * c;

        // condition check 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);
        }
        // Condition check for real and equal roots
        else if(determinant == 0) {
            root1 = root2 = -b / (2 * a);

            System.out.format("root1 = root2 = %.2f;", root1);
        }
        // If roots are 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);
        }
    }
}

Output

root1 = -0.87+1.30i and root2 = -0.87-1.30i

Leave a Reply