Pages

Sunday, November 1, 2020

Java Program to Find All Roots of a Quadratic Equation Using Formula

1. Overview

In this article, you'll learn how to find all the roots of a given quadratic equation using java programming language.

We'll use the if else condition and Math.sqrt() method to solve this problem.

You can look the best way to find the largest number among three numbers

Example:

Sample quadratic equation ax2 + by + c = 0

and here a, b and c are the real numbers where a !=  0.

First, we need to find the determinant of the quadratic equation. 

Formula for the determinant is b2 - 4ac.

Result of this equation tells the nature of the roots.

  • If determinant is greater than 0, the roots are real and different.
  • If determinant is equal to 0, the roots are real and equal.
  • If determinant is less than 0, the roots are complex and different. 
Java Program to Find All Roots of a Quadratic Equation Using Formula


2. Example To Find Roots Of Quadratic Equation using Formula

The below example is wrapped the core logic inside a separate function.

package com.javaprogramto.programs.equations;

public class RootsOfQuadraticEquationExample {

	public static void main(String[] args) {
		double a = 10;
		double b = 50;
		double c = 30;

		printRootsOfQuadraticEquation(a, b, c);

		a = 20;
		b = 20;
		c = 20;

		printRootsOfQuadraticEquation(a, b, c);

	}

	private static void printRootsOfQuadraticEquation(double a, double b, double c) {

		System.out.println("Inputs a : " + a + ", b : " + b + ", c : " + c);
		double determinant = b * b - 4 * a * c;
		double root1;
		double root2;

		// 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);
		}
		System.out.println("\n");

	}

}

Output:

Inputs a : 10.0, b : 50.0, c : 30.0
root1 = -0.70 and root2 = -4.30

Inputs a : 20.0, b : 20.0, c : 20.0
root1 = -0.50+0.87i and root2 = -0.50-0.87i

format() method is used to print the output in the desired format.

3. Conclusion

In this tutorial, you've seen how to calculate the roots of quadratic equation using formula.

Example program is hosted on the GitHub.

format()

No comments:

Post a Comment

Please do not add any spam links in the comments section.