A quadratic equation is a second-degree polynomial equation of the form: ax2+bx+c=0
where a, b, and c are constants, and x represents the unknown variable. In this tutorial, we will write a Python program to find the roots of a quadratic equation using the quadratic formula.
Quadratic Formula
The solutions (roots) of the quadratic equation are given by the formula:
\[x = (-b \pm \sqrt(b^2-4ac) \over 2a)\]
The term b² – 4ac is called the discriminant, which determines the nature of the roots:
- If b² – 4ac > 0, the equation has two real and distinct roots.
- If b² – 4ac = 0, the equation has one real root (repeated).
- If b² – 4ac < 0, the equation has complex (imaginary) roots.
Python Program to Solve a Quadratic Equation
import math # Taking user input for coefficients a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) c = float(input("Enter coefficient c: ")) # Calculating the discriminant discriminant = b**2 - 4*a*c # Checking the nature of the roots if discriminant > 0: root1 = (-b + math.sqrt(discriminant)) / (2 * a) root2 = (-b - math.sqrt(discriminant)) / (2 * a) print(f"The roots are real and distinct: {root1:.2f}, {root2:.2f}") elif discriminant == 0: root = -b / (2 * a) print(f"The root is real and repeated: {root:.2f}") else: real_part = -b / (2 * a) imaginary_part = math.sqrt(abs(discriminant)) / (2 * a) print(f"The roots are complex: {real_part:.2f} ± {imaginary_part:.2f}i")
Output 1
Enter coefficient a: 1 Enter coefficient b: 4 Enter coefficient c: 8 The roots are complex: -2.00 ± 2.00i
Output 2
Enter coefficient a: 1 Enter coefficient b: -3 Enter coefficient c: 2 The roots are real and distinct: 2.00, 1.00
Output 3
Enter coefficient a: 1 Enter coefficient b: -2 Enter coefficient c: 1 The root is real and repeated: 1.00