How to check the nature of roots of a Quadratic equation in Python

Solving the long-given mathematical formula of the discriminant to find the nature and values of the roots of the quadratic equation is sometimes a very tedious and time-consuming task. So in this article, we are going to check the roots of any given quadratic equation using python.

We know, that every quadratic equation has three parameters namely:

AX2+BX+C

  • coefficient of the term X2¬† that is “A”
  • coefficient of the term X that is “B”
  • a constant that is “C”

Discriminant is defined as:

D = (B2 – 4AC)

Python Program to Find the Nature of roots of a Quadratic equation

To check the nature of roots of the quadratic equation; we must check the value of it’s discriminant. For example, if we get the value of discriminant greater than 0 or can say positive then roots are “Distinct & Real”. Below here is the different conditions of the discriminant and its its value:-

  1. If “D>0” then roots are “Real and Distinct”.
  2. If “D=0” then roots are “Equal”.
  3. If “D<0” then roots are “Imaginary”.
for _ in range(int(input())): 
    A,B,C = map(int,input().split())
    print(Nature(A,B,C))

Here we will take values of coefficients of quadratic equation as inputs which are A, B, C in this case. We will then take a function named “Nature” in this case to pass the values¬† A, B, C and since we will be returning the values from the it hence; we will print it.

After this we will define the function with A, B, C values:

def Nature(A,B,C):

 # where A, B, C are the coefficients of the Quadratic equation (ax^2+bx+c)
    D = B**2 -  (4*A*C)   # d is the discriminants of the quadratic equation.
  
    if D>0: return "Real"
    if D==0: return "Equal"
    if D<0: return "Imaginary"

After defining the function, we will compute the value of discriminant which is “D”. According to the values of the discriminant, we will verify the nature of the roots. For that we will use “if” function which will check for the certain condition and return the value specified if found “True” otherwise it will move to the next condition.

def Nature(A,B,C):

 # where A, B, C are the coefficients of the Quadratic equation (ax^2+bx+c)
    D = B**2 -  (4*A*C)   # d is the discriminants of the quadratic equation.
  
    if D>0: return "Real"
    if D==0: return "Equal"
    if D<0: return "Imaginary"
  
for _ in range(int(input())): 
    A,B,C = map(int,input().split())
    print(Nature(A,B,C))
OUTPUT:
1

3 8 4

Real

First line in the output indicates the number of test cases and the second line defines the coefficients as input.

You may also learn:

Python program to solve Quadratic equation

Leave a Reply

Your email address will not be published.