Home / Programs / Python program to solve quadratic equation
Programming Example

Python program to solve quadratic equation

👁 247 Views
💻 Practical Program
📘 Step by Step Learning
Python program to solve quadratic equation

Information & Algorithm

Quadratic equation:

Quadratic equation is made from a Latin term "quadrates" which means square. It is a special type of equation having the form of:

ax2+bx+c=0

Here, "x" is unknown which you have to find and "a", "b", "c" specifies the numbers such that "a" is not equal to 0. If a = 0 then the equation becomes liner not quadratic anymore.

In the equation, a, b and c are called coefficients.

Let's take an example to solve the quadratic equation 8x2 + 16x + 8 = 0

Program Code

# import complex math module  
import cmath  
a = float(input('Enter a: '))  
b = float(input('Enter b: '))  
c = float(input('Enter 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 are {0} and {1}'.format(sol1,sol2))   

Output

Enter a: 8
Enter b: 5
Enter c: 9
The solution are (-0.3125-1.0135796712641785j) and (-0.3125+1.0135796712641785j)

Explanation

In the first line, we have imported the cmath module and we have defined three variables named a, b, and c which takes input from the user. Then, we calculated the discriminant using the formula. Using the cmath.sqrt() method, we have calculated two solutions and printed the result.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.