Python – Find Roots of Quadratic Equation

Contents

Python Program to Find Roots of a Quadratic Equation

To find the roots of a quadratic equation ax^2 + bx + c = 0 in Python, read the coefficients a, b, and c from the user, and we shall use the formula to find the roots of the equation.

Program

In this example, we read three numbers into a, b, and c, and find the roots of the equation.

Python Program

import cmath

a = float(input('Enter a : '))
b = float(input('Enter b : '))
c = float(input('Enter c : '))

den = (b**2) - (4*a*c)
root1 = (-b - cmath.sqrt(den))/(2*a)
root2 = (-b + cmath.sqrt(den))/(2*a)

print('root 1 : ', root1)
print('root 2 : ', root2)
Copy

Output #1

Enter a : 2
Enter b : 8
Enter c : 1
root 1 :  (-3.8708286933869704+0j)
root 2 :  (-0.12917130661302934+0j)

Output #2

Enter a : 8
Enter b : 1
Enter c : 9
root 1 :  (-0.0625-1.0588171466310885j)
root 2 :  (-0.0625+1.0588171466310885j)

Summary

In this Python Examples tutorial, we learned how to find the roots of a quadratic equation defined by the given coefficient values.

Related Tutorials

Code copied to clipboard successfully 👍