Java program to calculate the discriminant value

In this program, we will see how to calculate the value of discriminant for a given algebraic expression using Java programming language.

In algebra, the discriminant helps us to determine various properties of the roots of the given polynomial.

Below given is the general quadratic polynomial of degree two:

ax2 + bx + c

Also, we calculate discriminant of the equation using the formula:

b2 – 4ac

Following properties can be found out using this value:

  • If the discriminant is equal to zero, the polynomial has equal roots.
  • If the discriminant is positive and the coefficients are real. The polynomial has two real roots.

These are the conditions for making deductions from the discriminant:

  • If the discriminant is equal to zero. There is one solution.
  • If the discriminant is positive. There are two solutions.
  • Otherwise, if the discriminant is negative. No real solution.

Java Code:

import java.io.*;
public class prog{ 
    public static void main(String args[])throws IOException
    { 
        BufferedReader ob =new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the values of a,b and c :\n");
        int a=Integer.parseInt(ob.readLine()); 
        int b=Integer.parseInt(ob.readLine()); 
        int c=Integer.parseInt(ob.readLine()); 
        int discriminant = (int)Math.pow(b,2) - (4*a*c);  
        if (discriminant > 0){ 
            System.out.println("Discriminant is " + discriminant);
            System.out.println("Two Solutions"); 
        } 
        else if (discriminant == 0){ 
            System.out.println("Discriminant is " + discriminant); 
            System.out.println("One Solution"); 
        } 
        else { 
            System.out.println("Discriminant is "+ discriminant); 
            System.out.println("No real Solution"); 
        } 
    } 
} 

Further, we will prompt the user to enter the values of the coefficients of the polynomial. Java provides the BufferedReader class to get user input.

After creating its object, we will use the ob.readLine() method to read the value as a string. Since all types of inputs in Java are read as string. We parse it into an integer type.

Using these values, we will calculate the discriminant as per the formula.

Output:

Enter the values of a,b and c :

4   5   6

Discriminant is -71
Hence No Real Solutions

Also read,

Calculating Area of a Trapezoid using Java

Calculating the area of a parallelogram in Java

 

So we have learned how to calculate the discriminant value in Java.

Leave a Reply

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