Java Program to Find all Roots of a Quadratic Equation

Updated on December 4, 2024
Find all roots of a quadratic equation header image

Introduction

Solving quadratic equations is a fundamental task in mathematics and programming. A quadratic equation takes the form ( ax^2 + bx + c = 0 ), where ( a ), ( b ), and ( c ) are coefficients, and ( x ) represents the variable to be solved. Completing this task programmatically allows you to understand better numeric operations and conditional logic in Java.

In this article, you will learn how to develop a Java program that calculates and displays all possible roots of a quadratic equation. Explore different scenarios, such as when the equation has two real roots, one real root, or complex roots.

Implement the Quadratic Formula

The quadratic formula, ( x = \frac{{-b \pm \sqrt{{b^2 - 4ac}}}}{{2a}} ), is used to find the roots of a quadratic equation. The expression under the square root, ( b^2 - 4ac ), known as the discriminant, determines the nature of the roots.

Calculate the Discriminant

  1. Start by defining the coefficients ( a ), ( b ), and ( c ).

  2. Compute the discriminant using the formula ( b^2 - 4ac ).

    java
    double a = 1.0;
    double b = 5.0;
    double c = 6.0;
    double discriminant = b * b - 4 * a * c;
    

    This code snippet calculates the discriminant, which helps determine the nature of the roots (real or complex).

Determine the Nature of the Roots

  1. Use the discriminant to decide the conditions for real roots, one real root, or complex roots.

  2. Calculate the roots based on these conditions.

    java
    if (discriminant > 0) {
        double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
        double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
        System.out.println("Roots are " + root1 + " and " + root2);
    } else if (discriminant == 0) {
        double root = -b / (2 * a);
        System.out.println("Root is " + root);
    } else {
        double realPart = -b / (2 * a);
        double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
        System.out.println("Roots are " + realPart + " + " + imaginaryPart + "i and " + realPart + " - " + imaginaryPart + "i");
    }
    

    If the discriminant is positive, there are two distinct roots; if zero, there is exactly one real root; if negative, the roots are complex.

Conclusion

This Java program effectively determines and displays all possible roots of a quadratic equation based on the discriminant. Understanding and implementing the logic for the quadratic formula in Java enhances your grip on mathematical operations and conditional statements in programming. Apply these concepts to solve similar problems, like finding the roots of cubic equations or creating graphical solutions for equations.