0
0
PythonProgramBeginner · 2 min read

Python Program to Find Roots of Quadratic Equation

Use the quadratic formula in Python: calculate discriminant with 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

Inputa=1, b=-3, c=2
OutputRoots are 2.0 and 1.0
Inputa=1, b=2, c=1
OutputRoots are -1.0 and -1.0
Inputa=1, b=0, c=1
OutputRoots are complex: 0.0 + 1.0j and 0.0 - 1.0j
🧠

How to Think About It

To find roots of a quadratic equation ax² + bx + c = 0, first calculate the discriminant D = b² - 4ac. If D is positive, roots are two real numbers; if zero, roots are one real number repeated; if negative, roots are complex numbers. Use the formula (-b ± √D) / (2a) to find the roots.
📐

Algorithm

1
Get coefficients a, b, and c from the user
2
Calculate the discriminant D = b² - 4ac
3
If D is positive or zero, calculate two real roots using (-b ± √D) / (2a)
4
If D is negative, calculate complex roots using complex square root
5
Print the roots
💻

Code

python
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')
Output
Enter coefficient a: 1 Enter coefficient b: -3 Enter coefficient c: 2 Roots are 2.0 and 1.0
🔍

Dry Run

Let's trace the example a=1, b=-3, c=2 through the code

1

Input coefficients

a=1, b=-3, c=2

2

Calculate discriminant

d = (-3)**2 - 4*1*2 = 9 - 8 = 1

3

Check discriminant sign

d = 1 >= 0, so roots are real

4

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

5

Print roots

Roots are 2.0 and 1.0

StepDiscriminant (d)Root1Root2
Calculate d1
Calculate root112.0
Calculate root212.01.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

Using cmath module for all cases
python
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}')
This method handles real and complex roots uniformly but uses the cmath module which always returns complex numbers.
Using numpy.roots function
python
import numpy as np
coeffs = [1, -3, 2]
roots = np.roots(coeffs)
print(f'Roots are {roots[0]} and {roots[1]}')
This method is concise and uses a library function but requires numpy installed and does not show step-by-step calculation.

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.

ApproachTimeSpaceBest For
Manual calculation with if-elseO(1)O(1)Learning and simple scripts
Using cmath moduleO(1)O(1)Handling complex roots easily
Using numpy.rootsO(1)O(1)Polynomials of any degree with library support
💡
Always check if coefficient 'a' is zero to avoid division by zero error in quadratic formula.
⚠️
Beginners often forget to handle the case when discriminant is negative, causing errors when taking square root.