# Python program to find roots of a quadratic equation

## Roots of a quadratic equation in Python

Here, in this page we will discuss the program to find the roots of a quadratic equation in python . In this python program, we will learn how to find the roots of a quadratic equation[ax2 + bx + c]. When we try to solve the quadratic equation we find the root of the equation. Mainly roots of the quadratic equation are represented by parabola in 3 different patterns like

• No Real Roots
• One Real Root
• Two Real Roots

When we solve the equation we get 3 conditions mentioned above using this formula:-
X = [-b (+or-)[Squareroot(pow(b,2)-4ac)]]/2a

## Algorithm

• Step 1:- Start.
• Step 2:- Take user inputs for a,b and c.
• Step 3:- Check if the value of a is not zero.
• Step 4:- Calculate Functions value ie, b*b – a*a*c.
• Step 5:- Find the square root of the function.
• Step 6:-if the value is greater than zero print Two real roots and value of roots.
• Step 7:- If the value is equal to zero Print one real root and print the value.
• Step 8:- If both the condition are false print no real roots and print values.

## Python program to find the square root of a quadratic equation

```#import math library
import math
#take user inputs
a = int(input('Enter value of a :'))
b = int(input('Enter value of b :'))
c = int(input('Enter value of c :'))
#check for value of a
if a == 0:
print("a cannot be zero")
#if a is greater than 0
else:
#calculate value of Function
val = b**2 - 4 * a * c
root = math.sqrt(abs(val))
#Check for roots and print according to their nature
if val > 0:
print("Two Real Roots")
print((-b + root)/(2 * a))
print((-b - root)/(2 * a))
elif val == 0:
print("One Real Root")
print(-b / (2*a))
else:
print("No Real Root")
print(- b / (2*a) , " + i", root)
print(- b / (2*a) , " - i", root)```
`Output:Enter value of a :1Enter value of b :-7Enter value of c :12Two Real Roots4.03.0`

### One comment on “Python program to find roots of a quadratic equation”

• Om Prakash

Code in Java :
import java.util.Scanner;
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a:”);
int a = sc.nextInt();
System.out.print(“Enter b:”);
int b = sc.nextInt();
System.out.print(“Enter c:”);
int c = sc.nextInt();
int determinant = b*b – 4*a*c;
if(determinant > 0)
{
System.out.println(“Real roots: “);
double root1 = (-b + Math.sqrt(determinant) )/(2*a);
System.out.println(root1);
double root2 = (-b – Math.sqrt(determinant) )/(2*a);
System.out.println(root2);
}
else if(determinant < 0)
{
System.out.println("Imaginary roots: ");
double root1 = -b/(2*a);
double rootImg1 = Math.abs(Math.sqrt(determinant));
System.out.println(root1 +"+i"+rootImg1);
System.out.println(root1 +"-i"+rootImg1); // Imaginary root2
}
else
{
System.out.println("Equal roots: ");
System.out.println(-b/2*a);
System.out.println(-b/2*a);
}
}
}