0
0
PythonProgramBeginner · 2 min read

Python Program to Solve Quadratic Equation

You can solve a quadratic equation in Python by calculating the discriminant with 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

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.0i and 0.0 - 1.0i
🧠

How to Think About It

To solve a quadratic equation, first calculate the discriminant using 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

1
Get coefficients a, b, and c from the user
2
Calculate the discriminant as b squared minus 4 times a times c
3
If discriminant is positive or zero, calculate two real roots using the quadratic formula
4
If discriminant is negative, calculate real and imaginary parts for complex roots
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 = -b / (2*a)
        imag = (abs(d)**0.5) / (2*a)
        print(f'Roots are complex: {real} + {imag}i and {real} - {imag}i')
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 where 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) / 2 = 1.0

5

Print roots

Roots are 2.0 and 1.0

StepVariableValue
2d1
4root12.0
4root21.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

Using cmath module for complex roots
python
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}')
This method handles real and complex roots uniformly but requires importing cmath.
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 uses numpy library to find roots directly, useful for polynomial equations but requires numpy installed.

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.

ApproachTimeSpaceBest For
Direct formula with conditionalsO(1)O(1)Simple scripts without extra libraries
cmath moduleO(1)O(1)Handling complex roots uniformly
numpy.rootsO(1)O(1)Polynomials of any degree with numpy installed
💡
Always check if coefficient 'a' is zero to avoid division by zero errors.
⚠️
Beginners often forget to handle the case when the discriminant is negative, causing errors when taking square roots.