Java Program - Find Roots of a Quadratic Equation
A standard form of a quadratic equation is:
ax2 + bx + c = 0
Where:
a, b and c are real numbers and a ≠ 0.
Roots of the equation are:
For Example:
The roots of equation x2 + 5x + 4 = 0 is
The roots of the equation will be imaginary if D = b2 - 4ac < 0. For example - the roots of equation x2 + 4x + 5 = 0 will be
Example: Calculate roots of a Quadratic equation
In the example below, a method called roots is created which takes a, b and c as arguments to calculate the roots of the equation ax2 + bx + c = 0.
import java.lang.Math; public class MyClass { static void roots(double a, double b, double c) { double D = b*b - 4*a*c; if (D >= 0){ double x1 = (-b + Math.sqrt(D))/(2*a); double x2 = (-b - Math.sqrt(D))/(2*a); System.out.println("Roots are: "+ x1 + ", " + x2); } else { double x1 = -b/(2*a); double x2 = Math.sqrt(-D)/(2*a); System.out.println("Roots are: "+ x1 + " + " + x2 + "i"); System.out.println("Roots are: "+ x1 + " - " + x2 + "i"); } } public static void main(String[] args) { System.out.println("Equation is x*x+5x+4=0"); roots(1,5,4); System.out.println("\nEquation is x*x+4x+5=0"); roots(1,4,5); } }
The above code will give the following output:
Equation is x*x+5x+4=0 Roots are: -1.0, -4.0 Equation is x*x+4x+5=0 Roots are: -2.0 + 1.0i Roots are: -2.0 - 1.0i
Recommended Pages
- Java Program - To Check Prime Number
- Java Program - Bubble Sort
- Java Program - Selection Sort
- Java Program - Maximum Subarray Sum
- Java Program - Reverse digits of a given Integer
- Java - Swap two numbers
- Java Program - Fibonacci Sequence
- Java Program - Insertion Sort
- Java Program - Find Factorial of a Number
- Java Program - Find HCF of Two Numbers
- Java Program - Merge Sort
- Java Program - Shell Sort
- Stack in Java
- Queue in Java
- Java Program - Find LCM of Two Numbers
- Java Program - To Check Whether a Number is Palindrome or Not
- Java Program - To Check Whether a String is Palindrome or Not
- Java Program - Heap Sort
- Java Program - Quick Sort
- Java - Swap Two Numbers without using Temporary Variable