Python Program to Find Roots of Quadratic Equation
D = b**2 - 4*a*c, then find roots with root1 = (-b + D**0.5) / (2*a) and root2 = (-b - D**0.5) / (2*a).Examples
How to Think About It
Algorithm
Code
a = float(input('Enter coefficient a: ')) b = float(input('Enter coefficient b: ')) c = float(input('Enter coefficient c: ')) if a == 0: print('Coefficient a cannot be zero for a quadratic equation.') else: d = b**2 - 4*a*c if d >= 0: root1 = (-b + d**0.5) / (2*a) root2 = (-b - d**0.5) / (2*a) print(f'Roots are {root1} and {root2}') else: real_part = -b / (2*a) imag_part = (abs(d)**0.5) / (2*a) print(f'Roots are complex: {real_part} + {imag_part}j and {real_part} - {imag_part}j')
Dry Run
Let's trace the example a=1, b=-3, c=2 through the code
Input coefficients
a=1, b=-3, c=2
Calculate discriminant
d = (-3)**2 - 4*1*2 = 9 - 8 = 1
Check discriminant sign
d = 1 >= 0, so roots are real
Calculate roots
root1 = (-(-3) + 1**0.5) / (2*1) = (3 + 1) / 2 = 2.0 root2 = (-(-3) - 1**0.5) / (2*1) = (3 - 1) / 2 = 1.0
Print roots
Roots are 2.0 and 1.0
| Step | Discriminant (d) | Root1 | Root2 |
|---|---|---|---|
| Calculate d | 1 | ||
| Calculate root1 | 1 | 2.0 | |
| Calculate root2 | 1 | 2.0 | 1.0 |
Why This Works
Step 1: Calculate discriminant
The discriminant D = b**2 - 4*a*c tells us the nature of roots: positive means two real roots, zero means one real root, negative means complex roots.
Step 2: Compute roots for real discriminant
When D >= 0, roots are calculated using (-b ± sqrt(D)) / (2*a) which gives two real numbers.
Step 3: Handle complex roots
If D < 0, roots are complex. We calculate real and imaginary parts separately and display them as complex numbers.
Alternative Approaches
import cmath a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) if a == 0: print('Coefficient a cannot be zero for a quadratic equation.') else: d = cmath.sqrt(b**2 - 4*a*c) root1 = (-b + d) / (2*a) root2 = (-b - d) / (2*a) print(f'Roots are {root1} and {root2}')
import numpy as np coeffs = [1, -3, 2] roots = np.roots(coeffs) print(f'Roots are {roots[0]} and {roots[1]}')
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic operations and conditional checks, so it runs in constant time.
Space Complexity
Only a few variables are used to store inputs and results, so space usage is constant.
Which Approach is Fastest?
All approaches run in constant time; using cmath simplifies code for complex roots but adds module overhead, while numpy is heavier but useful for polynomial roots in general.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Manual calculation with if-else | O(1) | O(1) | Learning and simple scripts |
| Using cmath module | O(1) | O(1) | Handling complex roots easily |
| Using numpy.roots | O(1) | O(1) | Polynomials of any degree with library support |