How to find roots of polynomial in Java

Here in this context, we are going to learn how to find roots of a polynomial in Java.

So if want to find roots of a quadratic equation we first fetch the coefficient of x2 then x and then of constant.

If the discriminant is positive–if b2 -4ac > 0–then the quadratic equation has two solutions.
If the discriminant is zero–if b2 – 4ac = 0–then the quadratic equation has one solution.
If the discriminant is negative–if b2 -4ac < 0–then the quadratic equation has no solutions.

Also learn: How to calculate the area of polygon in Java

Java program to find roots of a polynomial

import java.io.*; 
import java.lang.Math.*;

class takingInput
{
 public static void main(String args[]) 
    { 
        double a,b,c;
        Scanner in=new Scanner(System.in);
        System.out.println("Enter the values of a b and c");
        a=in.nextDouble();
        b=in.nextDouble();
        c=in.nextDouble();
       findingRoots fr = new findingRoots(); 
       fr.calValue(a, b, c); 
    }  
}

class findingRoots
{ 
    void calValue(double a, double b, double c) 
    { 
        double dis;
        double root;
     if (a == 0) 
     { 
        System.out.println("It is not in quadratic form"); 
        return; 
     } 
   
      dis= Math.pow(b,2.0) - 4*a*c; 
      root = Math.sqrt(Math.abs(dis)); 
   
     if (dis > 0) 
     { 
        System.out.println("The roots of a given quadratic equation are real and different"); 
        System.out.print("Values of roots : ");
        System.out.println((double)(-b + root) / (2 * a) + ", " 
                            + (double)(-b - root) / (2 * a)); 
     } 
     else // dis < 0 
     { 
        System.out.println("The roots of a given quadratic equation are complex \n"); 
        System.out.print("Values of roots:");
        System.out.println( -(double)b / ( 2 * a ) + " + i" 
                          + root + ", "  + -(double)b / ( 2 * a ) 
                          + " - i" + root); 
     } 
    } 
}

Output:

Enter the values of a b and c:
4
-6
2
The roots of a given quadratic equation are real and different
Values of roots: 1, 0.5

Explanation:

In this code, we took values of a b and c from the user. When the user enters the value we pass those value to the function calValue.This function is defined under the class findingRoots.

In the function, first, we check the value of a if it is 0 means it is not a quadratic equation. Then we calculate the discriminant and check whether it is greater than 0, equal to 0 or less than zero.

Then we apply formula -b+sqrt(b2 -4ac)/2a and  -b-sqrt(b2 -4ac)/2a and print the result.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *