Python Program to Solve Quadratic Equation
discriminant = b**2 - 4*a*c and then finding roots using root1 = (-b + discriminant**0.5) / (2*a) and root2 = (-b - discriminant**0.5) / (2*a).Examples
How to Think About It
b**2 - 4*a*c. If the discriminant is positive, the equation has two real roots. If zero, one real root. If negative, roots are complex numbers. Use the quadratic formula to find the roots accordingly.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 = -b / (2*a) imag = (abs(d)**0.5) / (2*a) print(f'Roots are complex: {real} + {imag}i and {real} - {imag}i')
Dry Run
Let's trace the example where 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) / 2 = 1.0
Print roots
Roots are 2.0 and 1.0
| Step | Variable | Value |
|---|---|---|
| 2 | d | 1 |
| 4 | root1 | 2.0 |
| 4 | root2 | 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: Find 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 have real and imaginary parts. We calculate real part as -b/(2*a) and imaginary part as sqrt(-d)/(2*a).
Alternative Approaches
import cmath a = float(input('a: ')) b = float(input('b: ')) c = float(input('c: ')) 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 coefficients and roots, so space usage is constant.
Which Approach is Fastest?
The direct formula calculation is fastest and simplest; using libraries like cmath or numpy adds overhead but simplifies code for complex cases.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct formula with conditionals | O(1) | O(1) | Simple scripts without extra libraries |
| cmath module | O(1) | O(1) | Handling complex roots uniformly |
| numpy.roots | O(1) | O(1) | Polynomials of any degree with numpy installed |