In this Python Program, we will learn how to Solve Quadratic Equation.

In algebra, a **quadratic equation** is an equation that can be rearranged in standard form as

**ax²+bx+c = 0**

where *x* represents an unknown, and *a*, *b*, and *c* represent known numbers, where *a* ≠ 0. If *a* = 0, then the equation is linear, not quadratic, as there is no *ax*** 2** term. The numbers

A Quadratic Equation has at most two solutions, and they depend entirely upon the discriminant. If the discriminant > 0, then two distinct real roots exist for this equation. If discriminant = 0, two equal and real roots exist. Or if discriminant < 0, two distinct complex roots exist.

Here is the source code of the program to calculate the roots of a Quadratic Equation.

```
# Python Program to Solve Quadratic Equation
# Solve the quadratic equation ax**2 + bx + c = 0
# Import complex math module
import cmath
a = 1
b = -7
c = 12
# To take coefficient input from the user
# a = float(input('Enter the Value of a: '))
# b = float(input('Enter the Value of b: '))
# c = float(input('Enter the Value of c: '))
# calculate the discriminant
d = (b**2) - (4*a*c)
# find two solutions
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution is {0} and {1}'.format(sol1,sol2))
```

The solution is (3+0j) and (4+0j)

Another way to calculate the Quadratic Equation

```
# Python Program to Solve Quadratic Equation
# Import Module
import math
a = 1
b = -7
c = 12
# To take coefficient input from the user
# a = float(input("Enter the Value of a: "))
# b = float(input("Enter the Value of b: "))
# c = float(input("Enter the Value of c: "))
discriminant = (b * b) - (4 * a * c)
if(discriminant > 0):
root1 = (-b + math.sqrt(discriminant) / (2 * a))
root2 = (-b - math.sqrt(discriminant) / (2 * a))
print("Two Distinct Real Roots Exists: root1 = %.2f and root2 = %.2f" %(root1, root2))
elif(discriminant == 0):
root1 = root2 = -b / (2 * a)
print("Two Equal and Real Roots Exists: root1 = %.2f and root2 = %.2f" %(root1, root2))
elif(discriminant < 0):
root1 = root2 = -b / (2 * a)
imaginary = math.sqrt(-discriminant) / (2 * a)
print("Two Distinct Complex Roots Exists: root1 = %.2f+%.2f and root2 = %.2f-%.2f" %(root1, imaginary, root2, imaginary))
```

Two Distinct Real Roots Exists: root1 = 7.50 and root2 = 6.50

In the above program, we import the ** cmath module **to perform complex square root.

First, we need to calculate the discriminant and then find the two solutions of the quadratic equation.

## Comments