Program to Find Roots of a Quadratic Equation in Python
Finding Roots of a Quadratic Equation
A quadratic equation is in the form ax² + bx + c = 0. The roots of this equation can be real or complex depending on the discriminant (D = b² - 4ac).
We will explore three different methods to find the roots of a quadratic equation in Python.
Method 1: Using the Quadratic Formula
This method uses the quadratic formula: x = (-b ± sqrt(b² - 4ac)) / (2a).
import math def find_roots(a, b, c): discriminant = b**2 - 4*a*c if discriminant > 0: root1 = (-b + math.sqrt(discriminant)) / (2 * a) root2 = (-b - math.sqrt(discriminant)) / (2 * a) print(f"Real and Distinct Roots: {root1}, {root2}") elif discriminant == 0: root = -b / (2 * a) print(f"Real and Equal Roots: {root}") else: real_part = -b / (2 * a) imag_part = math.sqrt(-discriminant) / (2 * a) print(f"Complex Roots: {real_part} + {imag_part}i, {real_part} - {imag_part}i") # Get user input a, b, c = map(int, input("Enter coefficients a, b, and c: ").split()) find_roots(a, b, c)
Output: Real and Distinct Roots: 2.00, 1.00
Method 2: Using Factorization
Factorization is an alternative method where we break the middle term to find the roots.
def find_roots_factorization(a, b, c): found = False for i in range(-100, 101): for j in range(-100, 101): if i * j == a * c and i + j == b: print(f"Roots are: {-j}/{a} and {-i}/{a}") found = True return if not found: print("Cannot be factorized easily.") # Get user input a, b, c = map(int, input("Enter coefficients a, b, and c: ").split()) find_roots_factorization(a, b, c)
Output: Roots are: 2/1 and 3/1
Method 3: Using Recursion
This method recursively calculates the discriminant and finds the roots.
def find_roots_recursive(a, b, c, d): if d > 0: root1 = (-b + math.sqrt(d)) / (2 * a) root2 = (-b - math.sqrt(d)) / (2 * a) print(f"Real and Distinct Roots: {root1}, {root2}") elif d == 0: root = -b / (2 * a) print(f"Real and Equal Roots: {root}") else: real_part = -b / (2 * a) imag_part = math.sqrt(-d) / (2 * a) print(f"Complex Roots: {real_part} + {imag_part}i, {real_part} - {imag_part}i") def calculate_discriminant(a, b, c): d = b**2 - 4*a*c find_roots_recursive(a, b, c, d) # Get user input a, b, c = map(int, input("Enter coefficients a, b, and c: ").split()) calculate_discriminant(a, b, c)
Output: Complex Roots: -1.00 + 2.00i, -1.00 - 2.00i