Python Program to Solve the Quadratic Equation
In this post, we will discuss how to write a python program to solve the quadratic equation.
What is Quadratic Equation?
In algebra, a quadratic equation is an equation having the form
- ax2 + bx + c
where x represents an unknown variable, and a, b, and c represent known numbers such that a is not equal to 0.
The numbers a, b, and, c are the quadratic coefficients of the equation.
What do you mean by solving the Quadratic Equation?
Solving the Quadratic Equation means that we have to find the roots of the equation.
How to find the roots of the Quadratic Equation?
We use the Quadratic Formula to find the roots of the equation.
Firstly, we find the discriminant.
d = (b2) - (4*a*c)
And then we find the two roots using the discriminant.
r1 = (-b + sqrt(d)) / (2*a)r2 = (-b - sqrt(d)) / (2*a)
The nature of roots is decided by the value of discriminant.
If d > 0, the roots will be real;
If d < 0, the roots will be complex;
And if d = 0, the roots will be real and equal.
Let's see the code for this program.
# import complex math module import cmath # general quadratic equation is ax**2 + bx + c a = float(input("Enter the value of a: ")) b = float(input("Enter the value of b: ")) c = float(input("And Enter the value of c: ")) # printing the full equation print('The Quadratic Equation is ',a,'x**2 + ',b,'x + ',c,sep='') # calculating discriminant d = (b**2) - (4*a*c) # evaluating first root r1 = (-b + cmath.sqrt(d)) / (2*a) r2 = (-b - cmath.sqrt(d)) / (2*a) # prinring the roots print("First root:",r1) print("Second root:",r2)
Enter the value of b: 4
And Enter the value of c: 5
The Quadratic Equation is 8.0x**2 + 4.0x + 5.0
First root: (-0.25+0.75j)
Second root: (-0.25-0.75j)
I have used the sqrt() function from the cmath module to find the square root of the discriminant.
I have also used the sep parameter of the print() function so that I can format the quadratic equation properly. If you don't know what is sep parameter, you can check the Print Hello World program.
That was all about this python program.
Thanks for visiting our website. If you have any doubt, you can comment below.
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019