Java Program - Find Roots of a Quadratic Equation


Advertisements

A standard form of a quadratic quation is:

$$ax^2 + bx + c = 0$$

Where:

$$a, b$$ and $$c$$ are real numbers and $$a \ne 0$$.

Roots of the equation are:

$$\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$

For Example:

The roots of equation $$x^2 + 5x + 4 = 0$$ is

$$\frac{-5 \pm \sqrt{5^2 - 4\times1\times4}}{2\times1}$$ = $$\frac{-5 \pm \sqrt{9}}{2}$$ = $$\frac{-5 \pm 3}{2}$$ = $$-4, -1$$

The roots of the equation will be imaginari if $$D = b^2 - 4ac \lt 0$$. For example - the roots of equation $$x^2 + 4x + 5 = 0$$ will be

$$\frac{-4 \pm \sqrt{4^2 - 4\times1\times5}}{2\times1}$$ = $$\frac{-4 \pm \sqrt{-4}}{2}$$ = $$\frac{-4 \pm 2i}{2}$$ = $$-2 \pm i$$


Example: Calculate roots of a Quadratic equation

In the below example, a method called roots is created which takes $$a$$, $$b$$ and $$c$$ as arguemts to calculate the roots of the equation $$ax^2 + 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 of the equation ax^2 + bx + c = 0 are :");
      System.out.println(x1 + " and " + x2);
      System.out.println("Where a, b, c are " + a + "," + b + " and " + c + " respectively.");     
    } else {
      double x1 = -b/(2*a);
      double x2 = Math.sqrt(-D)/(2*a);
      System.out.println("Roots of the equation ax^2 + bx + c = 0 are imaginary.");
      System.out.println("Real part of root: " + x1);
      System.out.println("Imaginary part of root: " + x2);
      System.out.println("Where a, b, c are " + a + "," + b + " and " + c + " respectively."); 
    }
  }

  public static void main(String[] args) {
    roots(1,5,4);
    System.out.println();
    roots(1,4,5);
  }
}

Output

Roots of the equation ax^2 + bx + c = 0 are :
-1.0 and -4.0
Where a, b, c are 1 , 5 and 4 respectively.

Roots of the equation ax^2 + bx + c = 0 are imaginary.
Real part of root: -2.0
Imaginary part of root: -1.0
Where a, b, c are 1 , 4 and 5 respectively.



Recommended Pages


Advertisements